My Site
Categories
Django template autoescaping
Vimtips.org is running the SVN version of Django. This morning I ran an svn update, and I ran into my first API change. While looking at my site later on in the day, I noticed that both of my template filters were being HTML escaped, IE, things like < were showing up as &lt;.

My two filters are the pygments highlighting filter (you can see that in action in this article) and the filter that creates the category list at the end of every article (Under this article, it says "Filed Under: Programming, Python, Django").

Looking through the svn changelog, I noticed that they implemented a new feature, called autoescape, which will make every template variable and custom filters autoescape for safety. Using:

1
2
3
{% autoescape off %}
<a href='{{ link.url }}'>{{ link.name }}</a>
{% endautoescape %}

... you can turn off autoescaping. You can also use the Django template filter safe. As for custom filters, to make it so your returned string isn't autoescaped, you have to mark it as safe. Here I'm showing my category list filter with the new safestring.mark_safe() function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django.utils import safestring

@register.filterclass="nd">@register.filter class="p">(name='category_list')
def category_list(categories):
    """
        Shows all categories as a list of links separated by commas
    """
    c = []
    for category in categories:
        c.append("<a href='/category/%d'>%s</a>" % (category.id,
            category.name))

    return safestring.mark_safe(", ".join(c))
Filed under: Programming, Python, Django
Comments:

No comments have been added yet

Add a comment:
captcha

Optional, for comment reply notifications
 
Note: If you enter your email address, you will be subscribed to this article and will recieve comment updates via email. This is the only thing your address will be used for. A link will be provided at the end of each email that will allow you to unsubscribe should you need to, or you can go to http://synicworld.com//unsubscribe to unsubscribe from any/all updates.