4

I loaded a custom template tag note_extras.py in base.html.

base.html

<div id="wrap">
{% load note_extras %}    
{% block content %}
{% endblock %}
</div><!--wrap-->

but it is not accessible at templates which is an extend of base.html ie::

home.html

{% extends "base.html" %}
{% block content %}
<div class="container">
{% create_tagmenu request.user.pk %}
</div>
{% endblock %}

it is working fine if i load note_extras in home.html ie:

{% extends "base.html" %}
{% load note_extras %}
....
Community
  • 1
  • 1
suhailvs
  • 20,182
  • 14
  • 100
  • 98

3 Answers3

4

In Django template language, you must load all needed template libraries in each of the templates.

I personally think it is a good idea because it makes templates more explicit (which is better than implicit). Ill give an example. Prior to Django 1.5, the default behavior for a url tag was to provide the view name in plaintext as well as all the needed parameters:

{% url path.to.view ... %}

There however was no way to provide the path to the view via a context variable:

{% with var='path.to.view' %}
    {% url var ... %}
{% endwith %}

To solve that, starting with 1.3, you could import the future version of the url tag (which became the default in 1.5) by doing:

{% load url from future %}
{% url var ... %}
or
{% url 'path.to.view' ... %}

Now imagine that you would need to create a template which would extend from a base template which you did not create (e.g. one of django admin base templates). Then imagine that within the base template it would have {% load url from future %}. As a result, {% url path.to.view ... %} within your template would become invalid without any explicit explanation.

Of course this example does not matter anymore (starting with 1.5) however hopefully it illustrates a point that being explicit in templates is better than implicit which is why the currently implementation is the way it is.

miki725
  • 27,207
  • 17
  • 105
  • 121
  • 1
    I am also curious why it is not allowed to load all the tags in the base template. Perhaps this has changed after 3 years? – MadPhysicist Dec 16 '16 at 10:48
1

If you want that a template tag is loaded in every template you want to do it in the init file of your app:

from django.template.loader import add_to_builtins


add_to_builtins('my_app.templatetags.note_extras')
Goin
  • 3,856
  • 26
  • 44
1

In case anyone was wondering, add_to_builtins has been deprecated but one could still load a tag for all of the templates in the project via settings.TEMPLATES - supported for Django 1.9 onwards as described here: https://stackoverflow.com/a/59719364/2447803

slajma
  • 1,609
  • 15
  • 17