Custom template filter not working
django, django-template-filters, django-templates, python
Solution
According to the documentation:
For example, if your custom tags/filters are in a file called poll_extras.py, your app layout might look like this:
polls/
models.py
templatetags/
__init__.py
poll_extras.py
views.py
You have defined your templatefilter in views.py. It should be there:
yourapp/templatetags/__init__.py
yourapp/templatetags/yourapp_tags.py
First, create `yourapp/templatetags/` folder, and `yourapp/templatetags/__init__.py` empty file. Put your templatetag definition in yourapp_tags.py in that folder.
And in your template you would use the following:
{% load poll_extras %}
Finally, in your template, put {% load yourapp_tags %} to enable the templatetag.
Problem
views.py ``` from django import template register = template.Library() @register.filter def truncatesmart(value, limit=80): """ Truncates a string after a given number of chars keeping whole words. Usage: {{ string|truncatesmart }} {{ string|truncatesmart:50 }} """ try: limit = int(limit) # invalid literal for int() except ValueError: # Fail silently. return value # Make sure it's unicode value = unicode(value) # Return the string itself if length is smaller or equal to the limit if len(value) <= limit: return value # Cut the string value = value[:limit] # Break into words and remove the last words = value.split(' ')[:-1] # Join the words and return return ' '.join(words) + '...' ``` html ``` {% block content %} <div class="container-fluid"> <div class="container" id="content"> <div class="span3"> <div class="dashboard"> <div class="well smooth-edge2 shadow"> <div class="mini-info"> <div class="username"> <h2 class="text-center">{{rest.name|truncatesmart}}</h2> {% endblock %} ``` error ``` TemplateSyntaxError at /rprofile/info Invalid filter: 'truncatesmart' ``` doubt I am not able to understand why this custom filter is not working. While all other predefined filters such as title are working, this custom filter is not working at all.