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
templatemodule from Django is imported to work with custom template tags. -
The
format_htmlfunction fromdjango.utils.htmlis imported to safely format HTML strings. -
The
mark_safefunction fromdjango.utils.safestringis imported to mark the returned HTML string as safe, indicating that it doesn't need to be escaped when rendered in the template. -
The
registerobject, which is an instance oftemplate.Library(), is used to register the custom template tag. -
The
@register.simple_tagdecorator is applied to theget_boolean_imgfunction, indicating that it's a simple template tag that returns a value for use in the template. -
The
get_boolean_imgfunction takes one argumentvalue, which is the boolean value to be evaluated. -
Inside the function, it checks the value of the
valueargument:- If
valueis True, it returns an HTML icon represented by the CSS class "bi bi-check-lg" from Bootstrap Icons. - If
valueis False, it returns an HTML icon represented by the CSS class "bi bi-x" from Bootstrap Icons.
- If
-
The
format_htmlfunction 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>'))