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).
-
The
template
module from Django is imported to work with custom template tags. -
The
format_html
function fromdjango.utils.html
is imported to safely format HTML strings. -
The
mark_safe
function fromdjango.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. -
The
register
object, which is an instance oftemplate.Library()
, is used to register the custom template tag. -
The
@register.simple_tag
decorator is applied to theget_boolean_img
function, indicating that it's a simple template tag that returns a value for use in the template. -
The
get_boolean_img
function takes one argumentvalue
, which is the boolean value to be evaluated. -
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.
- If
-
The
format_html
function is used to create the HTML string safely and is marked as safe usingmark_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()
@register.simple_tag
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>'))