@register.filter(name='cf')
def cf(amount):
# Format the amount as an integer with commas
formatted_amount = f"{int(amount):,}"
# Determine the CSS class based on the sign of the amount
if amount < 0:
css_class = "red-text"
else:
css_class = "green-text"
print(formatted_amount)
# Generate the HTML markup with the CSS class and formatted amount
return f'<span class="{css_class}">{formatted_amount}</span>'
I am using the custom_filter inside the HTML, and the output is
<span class="green-text">5,492</span>
I just need ‘5,492’ in green color, but it prints as above
Please guide me to rectify it.
>Solution :
Just call mark_safe to mark string so django renders it in template.
from django.utils.safestring import mark_safe
@register.filter(name='cf')
def cf(amount):
# Format the amount as an integer with commas
formatted_amount = f"{int(amount):,}"
# Determine the CSS class based on the sign of the amount
if amount < 0:
css_class = "red-text"
else:
css_class = "green-text"
print(formatted_amount)
# Generate the HTML markup with the CSS class and formatted amount
return mark_safe(f'<span class="{css_class}">{formatted_amount}</span>')