往往制作模板的时候,我们会将一些公共部分,比如 header、footer、aside 等部分,抽离出来独立存放,不需要在每一个页面都重复编写,只需要在每一个页面引入它们即可。这个时候,我们可以使用 include 标签。
{% include "partial/header.html" %}
{% include "partial/footer.html" %}
include 可以将一个拆分出来的代码片段(fragment)嵌入到完整的文档中。使用形式是{% include "模板文件" %}
。
如果需要引入的模板不存在的话,它会报错,如我我们不知道引入的模板是否存在,则需要增加if_exists
判断。
{% include "partial/header.html" if_exists %}
这样如果 header.html 模板存在的话,则会引入,即使不存在,也不会报错,只是被忽略掉了。
默认情况下,include 引入的模板,它会继承当前模板的所有变量,如果想给 include 引入的模板增加另外的变量,可以使用with
来增加。如:
{% include "partial/header.html" with title="这是声明给header使用的title" %}
这样就给 include 引入的模板定义了 title 变量,当前模板的其他变量它同样也可以继续使用了。
如果需要声明多个变量给 include 引入的模板使用,可以连续使用key=value
的形式增加,它们之间使用空格隔开,如:
{% include "partial/header.html" with title="这是声明给header使用的title" keywords="这是声明给header使用的keywords" %}
如果只想让 include 引入的模板使用指定的几个变量,而不是当前模板的所有变量,可以使用 only 来做限制:
{% include "partial/header.html" with title="这是声明给header使用的title" keywords="这是声明给header使用的keywords" only %}
然后在 header.html 中使用:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
<meta name="keywords" content="{{keywords}}">
</head>