试图将命名空间和更多控件带到django的{%load%}标记中。
django-smart-load-tag的Python项目详细描述
试图将名称空间和更多控制权带给django的{% load %}标记。
这个项目包括两个标记:{% import %}和一个替换内置的{% load %}。两者都提供了相似的特性集。主要的区别在于,{% import %}命名空间在默认情况下,而{% load %}不在其中,保留了与django内置的{% load %}标记的向后兼容性。
安装
要安装,请首先使用以下任一方法将软件包安装到系统中:
pip install django-smart-load-tag easy_install django-smart-load-tag
然后,您必须通过在设置中添加“smart_load_tag”来安装到Django项目中。已安装的_应用程序。
如果要使用django智能加载标记而不将其加载到每个模板中,可以通过将其添加到内置标记中来进行全局安装。只需在urlconf中添加以下内容(通常是url.py):
from django.template import add_to_builtins add_to_builtins('smart_load_tag.templatetags.smart_load')
简介
加载后,智能^ {TT1}$tag替换现有的加载标签,因为它是向后兼容的。它提供了现有的负载标签缺少的特征:
模板标记命名空间:
{% load my_tags into cool_tags %} # Load library ``my_tags`` into namespace ``cool_tags``. {% cool_tags.my_tag %} # Usage of tag ``my_tag`` imported above as part of the template library ``my_tags``.
仅从库中加载一个标记:
{% load lib.tag_name %} # Load tag ``tag_name`` from templatetag library ``lib``. {% tag_name %} # Usage of tag imported above.
从特定应用程序加载库:
{% load lib from my_app %} # Ensure that library is loaded from my_app (by default, this will load the last library of that name in all your INSTALLED_APPS).
以不同名称加载标记
{% load my_tags.foo_tag as my_foo_tag %} # Load tag ``foo_tag`` from library ``my_tags`` and assign to name ``my_foo_tag`` {% my_foo_tag %} # Usage of tag imported above.
因此,标记的语法由这个psuedo regex描述:
{% load (lib_name(.tag_name)?( from app)?( as name)?( into namespace)?,? )+ %}
示例
可以接受from、as和into子句的任何组合:
{% load foo_tags.my_tag from my_app into cool_tags as my_cool_tag %} # lib foo_tags, tag my_tag, app my_app, namespace cool_tags, name my_cool_tag {% cool_tags.my_cool_tag %} # Usage
注意,into和as的组合不需要,因为以下两行是等效的:
{% load foo_tags.my_tag into cool_tags as my_cool_tag %} {% load foo_tags.my_tag as cool_tags.my_cool_tag %}
多个负载可以在同一行上,可以选择逗号分隔,从而实现更复杂的组合,例如:
{% load foo_tags from app1 into app1_foo_tags, foo_tags from app2, bar_tags.render_content as render_bar_content %} {% app1_foo_tags.render_content %} # from ``foo_tags from app1 into app1_foo_tags`` {% render_content %} # from ``foo_tags from app2`` {% render_bar_content %} # from ``bar_tags.render_content as render_bar_content``
django smart load tag提供的功能是一个渐进的增强,可以安全地加载到任何模板中,因为它与django的内置{% load %}标记保持向后兼容。
替代语法
替换的目的是向后兼容,但也存在一个新的标记,它提供了一个默认提供名称空间的语法,同时允许您选择退出加载的标记(使用的是)。下表说明了与smart{% load %}标记在语法上的差异。
{% import %} syntax {% load %} syntax {% import foo_tags %} {% load foo_tags into foo_tags %} {% import foo_tags from app1 %} {% load foo_tags from app1 into foo_tags %} {% import foo_tags.my_tag %} {% load foo_tags.my_tag as foo_tags.my_tag %} {% import foo_tags from my_app as my_foo %} {% load foo_tags from my_app into my_foo %} {% import foo_tags.my_tag as my_foo_tag %} {% load foo_tags.my_tag as my_foo_tag %} {% import * from foo_tags %} {% load foo_tags %} {% import * from foo_tags from app1 %} {% load foo_tags from app1 %}