Django custom template tags and filters

 


 

 Your custom tags and filters will live in a module inside the templatetags directory. 

 

 vim job/templatetags/clean_view.py

 

Code Example:

 

import re
from django import template
from django.template.defaultfilters import stringfilter
from datetime import datetime, timedelta
from django.conf import settings

register = template.Library()
    

@register.filter(is_safe=True)
@stringfilter
def cleandesc(value, arg):
    """
    {{ var|cleandesc:"bar" }}
    """
    arg = arg.strip()
    clean_text = value
    try:
        clean_text = clean_name(value, arg)
    except:
        pass
    clean_text = clean_text.replace(arg, "")
    clean_text = re.sub(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}', '', clean_text) # email 

      try:
        clean_text = replace_banned_keywords(clean_text)
    except:
        pass
    return clean_text

 

To load a filter or tag. Note application must already be installed in django setting.

 

 {% load clean_view %}

 Use your filter in template

{{ var|cleandesc:"bar" }} 

 

Comments