Is it possible to load a custom template tag in base and use it in extented templates

余生长醉 提交于 2019-12-10 20:31:34

问题


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 %}
....

回答1:


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.




回答2:


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')


来源:https://stackoverflow.com/questions/20560222/is-it-possible-to-load-a-custom-template-tag-in-base-and-use-it-in-extented-temp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!