django template tag for boolean image

Django -- Posted on June 10, 2022

This code is a custom Django template tag named get_boolean_img. It's used to render a specific HTML icon based on a boolean value (True or False).


  1. The template module from Django is imported to work with custom template tags.

  2. The format_html function from django.utils.html is imported to safely format HTML strings.

  3. The mark_safe function from django.utils.safestring is imported to mark the returned HTML string as safe, indicating that it doesn't need to be escaped when rendered in the template.

  4. The register object, which is an instance of template.Library(), is used to register the custom template tag.

  5. The @register.simple_tag decorator is applied to the get_boolean_img function, indicating that it's a simple template tag that returns a value for use in the template.

  6. The get_boolean_img function takes one argument value, which is the boolean value to be evaluated.

  7. Inside the function, it checks the value of the value argument:

    • If value is True, it returns an HTML icon represented by the CSS class "bi bi-check-lg" from Bootstrap Icons.
    • If value is False, it returns an HTML icon represented by the CSS class "bi bi-x" from Bootstrap Icons.
  8. The format_html function is used to create the HTML string safely and is marked as safe using mark_safe. This is important because it ensures that the icons won't be escaped when rendered in the template, allowing them to be displayed correctly.

                from django import template
from django.utils.html import format_html
from django.utils.safestring import mark_safe
register = template.Library()

def get_boolean_img(value):
    if value:
        return format_html(mark_safe('<i class="bi bi-check-lg"></i>'))
    return format_html(mark_safe('<i class="bi bi-x"></i>'))

Related Posts