【问题标题】:How can I show just the most recent post on my home page with jekyll?如何使用 jekyll 在我的主页上显示最近的帖子?
【发布时间】:2013-07-27 06:18:42
【问题描述】:
<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>

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

【问题讨论】:

    标签: templates jekyll templating liquid liquid-layout


    【解决方案1】:

    这可以通过使用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 %}
    

    【讨论】:

    • 这对我很有帮助,谢谢。但是在第一个示例中,我必须为 offset 设置一个值,否则第一个帖子不会出现。喜欢:{% for post in site.posts offset:1 limit:1 %}。也许它在最新版本的 Jekyll 中发生了变化。
    • Christian 您是否正在通过分页器或网站进行迭代以获取您的帖子?也许分页器是 1-indexed 之类的。
    • 不,抱歉。我正在使用:{% for post in site.posts limit:1 %}
    • 那一定是版本变更。实际上,考虑到 Jekyll 在 2013 年的重大更新,这是有道理的。我会四处寻找并更新这个答案..
    • 旁注,出于可访问性的原因,您只希望每页有一个 &lt;h1&gt; 标签。真棒回答,谢谢!很有帮助。
    【解决方案2】:

    与其创建循环,不如分配变量并继续...

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

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

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

    【讨论】:

    • 这适用于您只想显示一篇文章,但它会干扰在同一页面上列出其余文章。
    • 问的问题是“我只想显示一个帖子”,我的回答回答了这个问题。如果您稍后想要显示其他帖子,那么您创建一个 site.posts 循环偏移一个。这使您可以从帖子 #2 开始。如果您不熟悉,另一个答案会显示偏移量。
    【解决方案3】:

    如果您来到这里是因为标题中所述的问题,“如何使用 jekyll 在我的主页上显示最新的帖子?”而不是“如何在我的模板中仅显示最新帖子”,以下内容可能会有所帮助。

    给定一个全新的 Jekyll 版本 3.7.3 安装和默认的最小主题,创建一个文件,_layouts/home.html,包含以下内容:

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

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

    【讨论】:

    • 这应该是layout: null,而不是none
    • 这对我来说是最好的解决方案,因为它似乎保留了 page.url 和其他在其他解决方案中丢失的其他变量。这意味着您可以使用与其他帖子页面相同的布局页面。
    【解决方案4】:

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

    {%- assign latest_post = site.posts[0] -%}
    
    Latest post: <a href="{{ latest_post.url }}">{{ latest_post.title }}</a>
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 1970-01-01
      • 2020-08-22
      • 2017-10-11
      • 2012-06-07
      • 2013-03-07
      • 2018-03-22
      相关资源
      最近更新 更多