尝试为Django的{% load %}标签引入命名空间和更多控制。
项目描述
尝试为Django的{% load %}标签引入命名空间和更多控制。
此项目包含两个标签:{% import %}和内置{% load %}的替代品。两者提供类似的功能集。主要区别在于{% import %}默认使用命名空间,而{% load %}则不使用,以保留与Django内置{% load %}标签的向后兼容性。
安装
要安装,首先使用以下方法之一将包安装到您的系统上
pip install django-smart-load-tag easy_install django-smart-load-tag
然后您必须通过将“smart_load_tag”添加到settings.INSTALLED_APPS中将它安装到您的Django项目中。
如果您想在模板中不加载django-smart-load-tag的情况下使用它,您可以通过将其添加到内置标签中全局安装它。只需将以下内容添加到您的urlconf(通常是urls.py)中
from django.template import add_to_builtins add_to_builtins('smart_load_tag.templatetags.smart_load')
简介
加载后,智能{% load %}标签将替换现有的加载标签,因为它具有向后兼容性。它提供了现有加载标签缺乏的功能
模板标签命名空间
{% 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.
因此,标签的语法由以下伪正则表达式描述
{% 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 %}标签保持向后兼容。
替代语法
{% load %}替换旨在保持向后兼容,但还存在一个新的标签{% import %},它提供了一种默认提供命名空间的语法,同时允许您选择不将加载的标签命名空间化(使用* from)。
以下表格说明了与智能{% load %}标签的语法差异。
{% import %}语法
{% load %}语法
{% 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 %}