fcortes
fcortes

Reputation: 1368

Automatic addslashes while returing my own template tag in Django

I'm a noob django programmer and I want to create my own template tag for the Django templates. I've created a templatetags module and it seems to work properly when I use the shown code; However, my function returns a string with "&lt;" and "&gt;" instead of "<" and ">" (As if the result of the function would had been modified by addslashes() function). What's wrong with my code?

base_template.html (django template that uses my template tag)

<% load templatetags %>
<html>
 <head>
 </head>
 <body>
   {# text contains a string #}
   {{ text | formattedtext }}
 </body>
</html>

templatetags.py

from django import template

register = template.Library()
@register.filter(name='formattedtext')

def formattedtext(value):
    try:
        scoringTemplate = "<b>" + value + "</b>"
        print scoringTemplate #return string with "<b>text</b>"
        return scoringTemplate #however, this returns string with "&lt;text&gt;" value :(
    except ValueError:
        return value
    except:
        return value

Upvotes: 0

Views: 431

Answers (1)

karljacuncha
karljacuncha

Reputation: 164

You need to mark the output as 'safe': https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.safestring.mark_safe

So, your code should become:

from django import template
from django.utils.safestring import mark_safe

register = template.Library()
@register.filter(name='formattedtext')

def formattedtext(value):
    try:
        scoringTemplate = "<b>" + value + "</b>"
        print scoringTemplate #return string with "<b>text</b>"
        return mark_safe(scoringTemplate)   # unescaped, raw html
    except ValueError:
        return value
    except:
        return value

Upvotes: 2

Related Questions