Jekyll中的递增循环计数器

时间:2015-07-20 18:32:39

标签: html templates jekyll liquid

所以我试图在开始时创建一个只显示前10个帖子的页面。

完成这样,很简单:

<ul>
{% for post in site.posts limit:10 %}
    <li>//show post</li>
{% endfor %}
</ul>

然而它变得棘手,因为我想添加一个按钮,使下一个10个帖子可见。接着是另外10个帖子,直到显示网站上的每个帖子。

基本上,所有帖子都会在索引上生成,因为jekyll是静态的。但是第十篇文章之后的所有内容都将被js和css隐藏。但是,我还需要十点十分地生成这些帖子吗?

所以我试图做那样的事情

{% for post in site.posts limit:10 offset:9%}
     //show post
{% endfor %}

{% for post in site.posts limit:10 offset:19%}
     //show post
{% endfor %}

它仍然很糟糕,因为我必须为每十个帖子写一个循环,所以非常糟糕。所以基本上我必须创建一个循环,每10个帖子创建我的UL 10帖子。它归结为,我怎样才能每次增加10个偏移?我必须使用变量,但我不确定语法在这里是如何工作的?

这是我想要的html渲染:

<div id="first-ten"> 
    // ten posts
</div>

<div id="see-more-1">
    // ten posts
</div>

<div id="see-more-2">
    // ten posts
</div>

<div id="see-more-3">
    // last six posts for instance
</div>

1 个答案:

答案 0 :(得分:5)

我同意使用Liquid是一种奇怪的方式,但只是为了表明它可以做到:

---
---
{% comment %}Constant, can assign in _config.yml or YAML front matter if desired{% endcomment %}
{% assign postsPerPage = 2 %}

{% assign numPages = site.posts | size | divided_by: postsPerPage %}
{% comment %}Sketchy ceiling function since Liquid does integer division{% endcomment %}
{% if site.posts.size | modulo: postsPerPage > 0 %}
    {% assign numPages = numPages | plus: 1 %}
{% endif %}
Total pages: {{ numPages }}<br><br>
{% assign endIndex = numPages | minus: 1 %}

{% comment %}Output section{% endcomment %}
{% for pageNum in (0..endIndex) %}
  {% assign offset = pageNum | times: postsPerPage %}
  <div id="see-more-{{ pageNum }}" style="border-style: inset;">
  Page {{ pageNum }}:<br>
      <ol>
      {% assign posts = site.posts | sort: 'title' %}
      {% for post in posts limit: postsPerPage offset: offset %}
        <li>{{ post.title }}</li>
      {% endfor %}
      </ol>
  </div>
{% endfor %}

我已经在1-11个帖子中测试了上面的页面。我试着把它写成尽可能不言自明,因此有可能减少变量/计算量。

相关问题