数据文件

除了 Jekyll 的内建变量之外,你还可以指定用于 Liquid 模板系统 的自定义数据。

Jekyll 支持从 _data 目录下的 YAMLJSONCSVTSV载入数据。

注意 CSV 文件必须包含表头行。

这个强大的特性可以帮你避免模板中的重复,并能在不修改 _config.yml 的情况下设置网站特定的选项。

插件和主题也可以通过数据文件来配置变量。

数据目录

The _data folder is where you can store additional data for Jekyll to use when generating your site. These files must be YAML, JSON, or CSV files (using either the .yml, .yaml, .json or .csv extension), and they will be accessible via site.data.

示例: 成员列表

这是一个数据文件的简单示例,用以避免在模板中复制粘贴大段代码:

文件 _data/members.yml:

- name: Eric Mill
  github: konklone

- name: Parker Moore
  github: parkr

- name: Liu Fengyun
  github: liufengyun

文件 _data/members.csv:

name,github
Eric Mill,konklone
Parker Moore,parkr
Liu Fengyun,liufengyun

这些数据可以通过 site.data.members 访问(注意文件名决定了变量名)。

你现在可以在模板中使用该成员列表了:

<ul>
{% for member in site.data.members %}
  <li>
    <a href="https://github.com/{{ member.github }}">
      {{ member.name }}
    </a>
  </li>
{% endfor %}
</ul>

子目录

Data files can also be placed in sub-folders of the _data folder. Each folder level will be added to a variable’s namespace. The example below shows how GitHub organizations could be defined separately in a file under the orgs folder:

In _data/orgs/jekyll.yml:

username: jekyll
name: Jekyll
members:
  - name: Tom Preston-Werner
    github: mojombo

  - name: Parker Moore
    github: parkr

In _data/orgs/doeorg.yml:

username: doeorg
name: Doe Org
members:
  - name: John Doe
    github: jdoe

The organizations can then be accessed via site.data.orgs, followed by the file name:

<ul>
{% for org_hash in site.data.orgs %}
{% assign org = org_hash[1] %}
  <li>
    <a href="https://github.com/{{ org.username }}">
      {{ org.name }}
    </a>
    ({{ org.members | size }} members)
  </li>
{% endfor %}
</ul>

Example: Accessing a specific author

Pages and posts can also access a specific data item. The example below shows how to access a specific item:

_data/people.yml:

dave:
    name: David Smith
    twitter: DavidSilvaSmith

The author can then be specified as a page variable in a post’s front matter:

---
title: sample post
author: dave
---

{% assign author = site.data.people[page.author] %}
<a rel="author"
  href="https://twitter.com/{{ author.twitter }}"
  title="{{ author.name }}">
    {{ author.name }}
</a>

For information on how to build robust navigation for your site (especially if you have a documentation website or another type of Jekyll site with a lot of pages to organize), see Navigation.