Django: Filter to check if string contains substring

Out of all the handy filtery things that Django comes with, surprisingly it doesn't have one for checking if a string is contained within another.

Don't worry, thats easy enough to implement.

In a new template tag file:

from django import template
register = template.Library()

def contains(value, arg):
{% if text|contains:"http://" %}
This is a link.
{% else %}
Not a link.
{% endif %}

return arg in value

Now just make sure the tag file is loaded in the template before using.

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