include
标签容许在模板中包含其它的模板的内容。 标签的参数是所要包含的模板名称,能够是一个变量,也能够是用单/双引号硬编码的字符串。 每当在多个模板中出现相同的代码时,就应该考虑是否要使用 {% include %}
来减小重复 <br>html
假设咱们在多个 HTML 模板中都须要用到显示用户自定义的 HTML 片断,显示的方式是一个标题加上须要显示的具体内容。 下面的这个模板文件 html-section.html
就知足了基本的需求,咱们能够在不一样的 HTML 模板中引入这个子模版。 include
后面可使用字符串或者变量名来指定模板路径编码
<div class="section-title"> <span>{{title}}</span> </div> <div class="section-content"> <div id="{{section_id}}">{% autoescape off %}{{content | default:''}}{% endautoescape %}</div> </div>
在各个父模板中就可使用 include
指令来引入这个子模版。 因为默认状况下子模版能够访问复模版中的变量,子模版能够正常显示指定的 HTML 内容。spa
{% include 'html-section.html' %}
<br>.net
若是须要在一个网页屡次引入同一个子模版,上面的方式就会出现问题。 由于在子模版中咱们指定了变量名称,这个时候咱们可使用 with
关键字给子模版指定变量code
{% include 'html-section.html' with title="Summary" content=article_summary section_id="article-summary" %} {% include 'html-section.html' with title="Article Body" content=article_body section_id="article-body" %} {% include 'html-section.html' with title="Contact US" content=article_footer section_id="article-contact" %}
设想一下这样的场景:一个 HTML 页面中屡次引入了一个子模版,其中部分 include
语句须要作一些定制。<br> 好比说在变量后面加入固定的文字。<br> 固然能够经过修改子模版知足任意的定制化需求。但若是仅仅只是变量上的改变, 修改子模版就显得太繁琐。<br> 而 with
关键字能够在不改变子模版的前提下,使用过滤器来修改变量的值htm
<br> 假如咱们须要将上面的子模版作如下的修改:blog
在不改变子模版的前提下,咱们能够将 include 语句作如下的修改字符串
{% include 'html-section.html' with title=content|truncatewords:1|add:' Section'|capfirst content=article_footer section_id="article-contact" %}
with
指定的变量默认状况下子模版能够访问父模板的全部变量,在 Django 中还能够经过使用 only
选项来阻止这个默认行为get
{% include "html-section.html" with title="Summary" content=article_summary section_id="article-summary" only %}
<br>it
另外 Django 还提供了单独的 with
标签来修改或者指定变量的值。 能够单独使用,也能够搭配 include
标签使用。使用方法以下:
<!-- 使用 with 标签指定变量 --> {% with title="summary" content=article_body|capfirst section_id="article-body" %} {% include 'html-section.html' %} {% endwith %} <!-- 使用 with as --> {% with content|truncatewords:1|capfirst as title %} {% include 'html-section.html'%} {% endwith %}
<br><br> 转载请注明出处: zf-l