5

When doing the {% load custom_filters %} in the template, after {% extends "base.html" %} everything works fine, but when I move the load to the base.html template the filter gets a weird behaviour. This is my custom_filters.py:

from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

# To cut off strings at a specified character, at first occurance. Example:
#   time = 19:30:12.123456
#   {{ time|cut:'.' }}
#   returns: 19:30:12
@register.filter
@stringfilter
def cut(string, cutoff_point):
    return string.split(cutoff_point, 1)[0]

When I load it in the 'end-template' the behaviour is as expected. If time = 19:30:12.123456 then {{ time|cut:'.' }} returns 19:30:12. When I load it in base.html the returned value is 19:30:12123456, the same as the input but without the 'cutoff-point'.

Does anyone know why?

cezar
  • 11,616
  • 6
  • 48
  • 84
olofom
  • 6,233
  • 11
  • 37
  • 50

1 Answers1

13

You should place {% load ... %} in every template, where you want to use your custom tag or filter.

In your case it's also not a good idea to call a filter cut, because this filter already exists (and it's used to cut a dot from your string).

DrTyrsa
  • 31,014
  • 7
  • 86
  • 86
  • 1
    Oh, I must have missed that. That explains why it did the strange behaviour. But there's got to be a way to do the load in the base template, that's the idea of including/inheritance - not to have to write the same piece of code in 100 places. – olofom May 03 '12 at 08:19
  • @olofom It is how [Django works](https://docs.djangoproject.com/en/dev/topics/templates/#custom-libraries-and-template-inheritance). But you can use one [nice undocumented trick](http://stackoverflow.com/questions/1184983/load-a-django-template-tag-library-for-all-views-by-default). And take a good look at Carl Meyer's comment. – DrTyrsa May 03 '12 at 08:27
  • Ok, makes sense. Well then, I should just load it in every template then after all. Thanks! – olofom May 03 '12 at 08:53
  • load 3 dots? or load what? – oruchkin Sep 06 '22 at 13:22