包含

include 标记允许您包含存储在 _includes 文件夹中的另一个文件的内容

{% include footer.html %}

Jekyll 将在源目录根目录的 _includes 目录中查找引用的文件(在本例中为 footer.html),并插入其内容。

相对于另一个文件包含文件

您可以使用 include_relative 标记相对于当前文件包含文件片段

{% include_relative somedir/footer.html %}

您无需将包含的内容放在 _includes 目录中。相反,包含内容相对于使用该标记的文件。例如,如果 _posts/2014-09-03-my-file.markdown 使用 include_relative 标记,则包含的文件必须位于 _posts 目录或其子目录之一中。

请注意,您不能使用 ../ 语法指定引用更高级别目录的包含位置。

include_relative 标记可以使用 include 标记的所有其他功能,例如变量。

对包含文件使用变量名称

您要嵌入的文件的名称可以指定为变量,而不是实际的文件名称。例如,假设您在页面的前端内容中定义了一个变量,如下所示

---
title: My page
my_variable: footer_company_a.html
---

然后您可以在包含内容中引用该变量

{% if page.my_variable %}
  {% include {{ page.my_variable }} %}
{% endif %}

在此示例中,包含内容将插入 _includes/footer_company_a.html 目录中的文件 footer_company_a.html

将参数传递给包含内容

您还可以向包含项传递参数。例如,假设您在 _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 note.html content="This is my sample note." %}

content(即 This is my sample note)将插入到 {{ include.content }} 参数中。

当您希望从 Markdown 内容中隐藏复杂的格式时,向包含项传递参数尤其有用。

例如,假设您有一个具有复杂格式的特殊图像语法,并且您不希望作者记住复杂的格式。因此,您决定通过使用带有参数的包含项来简化格式。以下是您可能希望使用包含项填充的特殊图像语法的示例

<figure>
   <a href="https://jekyll.ruby-lang.org.cn">
   <img src="logo.png" style="max-width: 200px;"
      alt="Jekyll logo" />
   </a>
   <figcaption>This is the Jekyll 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>

此包含项包含 5 个参数

  • url
  • max-width
  • file
  • alt
  • caption

以下是一个将所有参数传递给此包含项的示例(包含项文件名为 image.html

{% include image.html url="https://jekyll.ruby-lang.org.cn"
max-width="200px" file="logo.png" alt="Jekyll logo"
caption="This is the Jekyll logo." %}

结果是前面显示的原始 HTML 代码。

为了保护用户不提供参数值的情况,您可以使用 Liquid 的 default 过滤器

总体而言,您可以创建包含项,这些包含项充当各种用途的模板——插入音频或视频剪辑、警报、特殊格式等。请注意,您应该避免使用太多包含项,因为这会减慢您网站的构建时间。例如,不要在每次插入图像时都使用包含项。(上述技术展示了特殊图像的用例。)

将参数变量传递给包含项

假设你要传递给 include 的参数是一个变量,而不是一个字符串。例如,你可能使用 {{ site.product_name }} 来引用产品的每个实例,而不是实际的硬编码名称。(在这种情况下,你的 _config.yml 文件将有一个名为 product_name 的键,其值为你的产品名称。)

传递给 include 参数的字符串不能包含大括号。例如,你不能传递包含以下内容的参数:"{{ site.product_name }} 的最新版本现已推出。"

如果你想将此变量包含在你传递给 include 的参数中,你需要在将它传递给 include 之前将整个参数存储为一个变量。你可以使用 capture 标记来创建变量

{% capture download_note %}
The latest version of {{ site.product_name }} is now available.
{% endcapture %}

然后将此捕获变量传递到 include 的参数中。省略参数内容周围的引号,因为它不再是一个字符串(它是一个变量)

{% include note.html content=download_note %}