Includes 详细教程(引入文件、包含文件、可复用片段、模板片段)
include
标签允许你引入存放在 _includes
文件夹中的其他文件的内容:
{% include footer.html %}
Jekyll 会在站点根目录下的 _includes
文件夹中查找 footer.html
,并将其内容插入到当前位置。
include_relative 相对于当前文件引入其他文件
你可以使用 include_relative
标签,使引入的文件路径相对于当前文件所在的位置:
{% include_relative somedir/footer.html %}
使用 include_relative
时,被引入的文件不需要放在 _includes
目录下,而是相对于使用该标签的文件。例如,如果 _posts/2014-09-03-my-file.markdown
文件中使用了 include_relative
,那么被引入的文件必须位于 _posts
目录或其子目录中。
需要注意的是,include_relative
不能使用 ../
这样的路径语法来引用上级目录的文件。
此外,include_relative
具有 include
标签的所有功能,例如可以使用变量。
使用变量作为 include 引入文件的名称
你可以使用变量来指定要引入的文件,而不仅仅是直接写文件名。例如,在页面的 Front Matter(页面头部参数)中定义一个变量:
---
title: My page
my_variable: footer_company_a.html
---
然后,在 include
标签中引用该变量:
{% if page.my_variable %}
{% include {{ page.my_variable }} %}
{% endif %}
在这个例子中,include
会插入 _includes/footer_company_a.html
目录下的 footer_company_a.html
文件的内容。
向 Includes 传递参数
你还可以向 include
传递参数。例如,假设你在 _includes
文件夹中有一个名为 note.html
的文件,内容如下:
<div markdown="span" class="alert alert-info" role="alert">
<i class="fa fa-info-circle"></i> <b>Note:</b>
{{ include.content }}
</div>
其中 {{ include.content }}
是一个参数,在调用 include
时传入值,例如:
{% include note.html content="JekyllDo.cn 写下的一段笔记." %}
这里,content
的值(即 JekyllDo.cn 写下的一段笔记
)会被插入到 {{ include.content }} 位置。
向 include
传递参数特别有用,当你想将复杂的格式化内容从 Markdown 内容中隐藏时。
例如,假设你有一个特殊的图片语法,其中包含复杂的格式化,并且不希望作者记住这些复杂的格式化规则。为此,你决定通过使用 include
和参数来简化格式。以下是你可能希望通过 include
填充的特殊图片语法示例:
<figure>
<a href="https://jekylldo.cn">
<img src="logo.png" style="max-width: 200px;"
alt="JekyllDo logo" />
</a>
<figcaption>这是 JekyllDo 的 LOGO</figcaption>
</figure>
你可以将这个内容模板化,并将每个值作为参数提供,例如:
<figure>
<a href="{{ include.url }}">
<img src="{{ include.file }}" style="max-width: {{ include.max-width }};"
alt="{{ include.alt }}"/>
</a>
<figcaption>{{ include.caption }}</figcaption>
</figure>
这个 include
包含了 5 个参数:
url
max-width
file
alt
caption
以下是传递所有参数的示例(include
文件名为 image.html
):
{% include image.html url="http://jekylldo.cn"
max-width="200px" file="logo.png" alt="JekyllDo logo"
caption="这是 JekyllDo 的 LOGO" %}
输出的结果会和之前原始的 HTML 代码一致。
为了防止用户未提供参数值的情况,你可以使用 Liquid 的 default 过滤器。
总的来说,你可以创建作为模板的 include
,用于各种用途——插入音频或视频片段、警告框、特殊格式等。需要注意的是,应该避免使用过多的 include
,因为这会导致网站的构建时间变慢。例如,不要每次插入图片时都使用 include
(上面展示的技术是用于特殊图片的用例)。
向 Includes 传递参数变量
假设你想传递给 include
的参数是一个变量,而不是一个字符串。例如,你可能会使用 {{ site.product_name }}
来表示每个产品实例,而不是硬编码的产品名称。(在这种情况下,你的 _config.yml
文件中会有一个名为 product_name
的键,并且其值是你产品的名称。)
你传递给 include
参数的字符串不能包含大括号。例如,你不能传递一个包含以下内容的参数: "The latest version of {{ site.product_name }} is now available."
如果你想在传递给 include
的参数中包含这个变量,你需要在传递给 include
之前先将整个参数存储为一个变量。你可以使用 capture
标签来创建这个变量:
{% capture download_note %}
The latest version of {{ site.product_name }} is now available.
{% endcapture %}
然后将这个捕获的变量传递给 include
的参数。省略参数内容两边的引号,因为它不再是字符串(它是一个变量):
{% include note.html content=download_note %}