Django: Capture blocks of template data and apply filters

The ability for Django to spit data out to the template so easily using tags and filters is really one of its strengths.

However, if you need to alter the output of some tags and they don't support an option to store the data as a context variable, things might get a little hairy.

Luckily, there is an easy way to apply filters to that data and its even built into the framework.

Use the "filter" tag to apply one or more filters to the data.

<a href="/do/something/here?url={% filter urlencode %}
{% url video-feed '' %}pubid;{{ article.source_publication.pubid }};id;{{ }}
{% endfilter %}&ampid=42" target="_blank">hello</a>

This will apply the urlencode filter to the output URL only, and the rest of the URL will remain untouched.

You can also chain the filters as you do normally, so there isn't a need to nest the filter tags.

{% filter force_escape|lower %}

If you're looking for a way to capture the actual template output to a variable, then use the captureas template tag.

Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog