Login

Verbose template filter : avoid too many if

Author:
romain-hardouin
Posted:
June 11, 2008
Language:
Python
Version:
.96
Score:
9 (after 9 ratings)

This tiny template filter saves you the tedious test "if this variable is set, print this text based on this variable".

'verbose' filter takes one parameter : a string containing '%s' which is a placeholder for the value to test. Check those examples :

  • Replace this :

    {% if name %} Hello {{ name }}, this is a dummy text {% endif %}

  • By this :

    {{ name|verbose:"Hello %s this is a dummy text" }}

This is also usefull for HTML :

{{ image|verbose:"<img src=\"%s\" />" }}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django import template                  

register = template.Library()

@register.filter
def verbose(value, arg):
    try:    
        if not value:
            return ''
        return arg % value
    except Exception:
        return str(value)
 

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

carljm (on June 16, 2008):

Good stuff, very handy. If used for HTML as in the last example, don't forget to tag on the |safe filter, too.

#

Please login first before commenting.