如何在jekyll上显示我主页上的最新帖子?

时间:2013-07-26 20:28:35

标签: templates jekyll templating liquid liquid-layout

<ul class="entries">
  {% for post in paginator.posts %}
  <li>
    <a href="{{ post.url }}">
    <h3>{{ post.title }}</h3>
    <p class="blogdate">{{ post.date | date: "%d %B %Y" }}</p>
    <div>{{ post.content |truncatehtml | truncatewords: 60 }}</div>
    </a>
  </li>
  {% endfor %}
</ul>

这显示了我的所有帖子,我只想展示最新的帖子。

4 个答案:

答案 0 :(得分:99)

这可以通过使用limit

来实现
{% for post in site.posts limit:1 %}
... Show the post ...
{% endfor %}

您还可以同时使用limitoffset来“展示”您最近的帖子:

<h1>Latest Post</h1>
{% for post in site.posts limit:1 %}
... Show the first post all big ...
{% endfor %}
<h1>Recent Posts</h1>
{% for post in site.posts offset:1 limit:2 %}
... Show the next two posts ...
{% endfor %}

答案 1 :(得分:16)

不是创建一个循环,只需分配变量并继续......

{% assign post = site.posts.first %}

(编辑2018)由于有人想知道如何在完成此操作后迭代其他帖子:

{% for post in site.posts offset:1 %}
  ... Show the next posts ...
{% endfor %}

答案 2 :(得分:4)

如果您按照标题中的说明来到这里,“我怎样才能在jekyll的主页上显示最近的帖子?”而不是“我如何仅显示模板中的最新帖子”,以下内容可能会有所帮助。

如果安装了带有默认最小主题的全新Jekyll版本3.7.3,请创建一个文件_layouts/home.html,其中包含以下内容:

---
layout: none
---
{{ site.posts.first }}

使Jekyll 3.7.3使用帖子模板显示第一篇帖子作为主页。

答案 3 :(得分:0)

似乎您也可以通过site.posts的第一个索引访问最新帖子,如下所示:

{%- assign latest_post = site.posts[0] -%}

Latest post: <a href="{{ latest_post.url }}">{{ latest_post.title }}</a>

尽管site.posts.first也可以像其他人提到的那样工作,但上面的示例还提供了一种一致的方式来访问除第一个索引以外的其他索引(并非您需要的)。另外,我没有足够的声誉来代替将此答案添加为评论:)