Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django template use custom filter in CSS

@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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading