Django 模板中 include 标签使用小结

时间:2023-03-08 20:48:00
Django 模板中 include 标签使用小结

include 标签允许在模板中包含其它的模板的内容。 标签的参数是所要包含的模板名称,可以是一个变量,也可以是用单/双引号硬编码的字符串。 每当在多个模板中出现相同的代码时,就应该考虑是否要使用 {% include %} 来减少重复

1. include 标签的基本用法

假设我们在多个 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 内容。

{% include 'html-section.html' %}

## 2. include with

如果需要在一个网页多次引入同一个子模版,上面的方式就会出现问题。

因为在子模版中我们指定了变量名称,这个时候我们可以使用 with 关键字给子模版指定变量

{% 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" %}

### 2.1 使用过滤器修改变量

设想一下这样的场景:一个 HTML 页面中多次引入了一个子模版,其中部分 include 语句需要做一些定制。

比如说在变量后面加入固定的文字。

当然可以通过修改子模版满足任意的定制化需求。但如果仅仅只是变量上的改变, 修改子模版就显得太繁琐。

with 关键字可以在不改变子模版的前提下,使用过滤器来修改变量的值

假如我们需要将上面的子模版做以下的修改:

  • 使用 content 里面的第一个单词作为标题
  • 所有的标题后面添加指定的内容
  • 标题的第一个字母要保证大写

在不改变子模版的前提下,我们可以将 include 语句做以下的修改

{% include 'html-section.html' with title=content|truncatewords:1|add:' Section'|capfirst content=article_footer section_id="article-contact" %}

### 2.2 阻止子模版访问除了 `with` 指定的变量

默认情况下子模版可以访问父模板的所有变量,在 Django 中还可以通过使用 only 选项来阻止这个默认行为

{% include "html-section.html" with title="Summary" content=article_summary section_id="article-summary" only %}

## 3. with 标签

另外 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 %}

转载请注明出处: [zf-l](http://www.cnblogs.com/zf-l/p/django-include.html)