Django: Filter to check if string contains substring

2 Comments

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:

01.from django import template
02.register = template.Library()
03. 
04.@register.filter()
05.def contains(value, arg):
06.  """
07.  Usage:
08.  {% if text|contains:"http://" %}
09.  This is a link.
10.  {% else %}
11.  Not a link.
12.  {% endif %}
13.  """
14.   
15.  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