分步教程
8. 博客
你可能想知道如何在没有数据库的情况下拥有一个博客。真正的 Jekyll 风格是仅使用文本文件来支持博客。
文章
博客文章位于名为 _posts
的文件夹中。文章的文件名具有特殊格式:发布日期,然后是标题,后跟扩展名。
在 _posts/2018-08-20-bananas.md
中创建你的第一篇文章,内容如下
---
layout: post
author: jill
---
A banana is an edible fruit – botanically a berry – produced by several
kinds of large herbaceous flowering plants in the genus Musa.
In some countries, bananas used for cooking may be called "plantains",
distinguishing them from dessert bananas. The fruit is variable in size,
color, and firmness, but is usually elongated and curved, with soft
flesh rich in starch covered with a rind, which may be green, yellow,
red, purple, or brown when ripe.
这类似于你之前创建的 about.md
,但它有一个作者和不同的布局。 author
是一个自定义变量,它不是必需的,可以命名为 creator
之类的内容。
布局
post
布局不存在,因此你需要在 _layouts/post.html
中创建它,内容如下
---
layout: default
---
<h1>{{ page.title }}</h1>
<p>{{ page.date | date_to_string }} - {{ page.author }}</p>
{{ content }}
这是一个布局继承的示例。文章布局输出标题、日期、作者和内容正文,这些内容由默认布局包装。
还要注意 date_to_string
过滤器,它将日期格式化为更漂亮的格式。
列出文章
目前没有办法导航到博客文章。通常,博客有一个页面列出所有文章,我们接下来就来做这件事。
Jekyll 在 site.posts
中提供文章。
在根目录中创建 blog.html
(/blog.html
),内容如下
---
layout: default
title: Blog
---
<h1>Latest Posts</h1>
<ul>
{% for post in site.posts %}
<li>
<h2><a href="{{ post.url }}">{{ post.title }}</a></h2>
{{ post.excerpt }}
</li>
{% endfor %}
</ul>
需要注意此代码中的几件事
post.url
由 Jekyll 自动设置为帖子的输出路径post.title
从帖子文件名中提取,可以通过在 front matter 中设置title
来覆盖post.excerpt
默认情况下是内容的第一段
你还需要一种方法通过主导航栏导航到此页面。打开 _data/navigation.yml
并为博客页面添加一个条目
- name: Home
link: /
- name: About
link: /about.html
- name: Blog
link: /blog.html
更多帖子
只有一个帖子的博客没什么意思。再添加几个
_posts/2018-08-21-apples.md
:
---
layout: post
author: jill
---
An apple is a sweet, edible fruit produced by an apple tree.
Apple trees are cultivated worldwide, and are the most widely grown
species in the genus Malus. The tree originated in Central Asia, where
its wild ancestor, Malus sieversii, is still found today. Apples have
been grown for thousands of years in Asia and Europe, and were brought
to North America by European colonists.
_posts/2018-08-22-kiwifruit.md
:
---
layout: post
author: ted
---
Kiwifruit (often abbreviated as kiwi), or Chinese gooseberry is the
edible berry of several species of woody vines in the genus Actinidia.
The most common cultivar group of kiwifruit is oval, about the size of
a large hen's egg (5–8 cm (2.0–3.1 in) in length and 4.5–5.5 cm
(1.8–2.2 in) in diameter). It has a fibrous, dull greenish-brown skin
and bright green or golden flesh with rows of tiny, black, edible
seeds. The fruit has a soft texture, with a sweet and unique flavor.
打开 http://localhost:4000,浏览你的博客帖子。
接下来,我们将重点介绍为每个帖子作者创建一个页面。