【问题标题】:Printing tag in Jekyll prints entire post and other problems在 Jekyll 中打印标签会打印整个帖子和其他问题
【发布时间】:2014-10-31 05:48:59
【问题描述】:

所以基本上我有this problem。我想将类别名称打印为标题,但是到目前为止,我尝试过的任何内容都无法使用包含多个单词的类别,因此我已经解决了在每个帖子中设置标签和类别的问题。

所以在做出这个决定后,我测试了 2 个标签和 2 个类别,tag1 用于 cat1tag2 用于 cat2,其中每个标签都有一个对应的类别。然后我将这些标签/猫对添加到我的一些帖子中。我的算法是这样的:

for loop in tags

    print category in a heading tag

        for loop in posts of that category

            print some post info

翻译成代码如下:

{% assign i = 0 %}
{% for TAG in site.tags %}
    <p>Checking the i: {{ i }}</p> 
    <p>Checking the tag: {{ TAG }}</p> 
    <h1>Checking the cat: {{ site.categories[i] }}</h1> 

    {% for post in site.tags.TAG %}
        <p>{{ post.title }}</p>
    {% endfor %}
    {% assign i = i + 1 %}
{% endfor %}

输出是:

Checking the i: 0
Checking the tag: tag1
THE WHOLE POST
Checking the cat: (nothing is printed here)

Checking the i: 0
Checking the tag: 0
Checking the cat: (nothing is printed here)

然后它就停止了。

所以我的问题是:

  • 如何访问类别?现在它什么也没打印
  • 为什么在标签后打印整个帖子内容?
  • 为什么只打印一个标签?
  • 为什么i 在循环结束时不递增?

【问题讨论】:

    标签: arrays loops jekyll


    【解决方案1】:

    如何访问分类?现在它什么也没打印

    网站类别是一个哈希:

    Hash
    {"github issue"=>[#Jekyll:Post, #Jekyll:Post],
     "toto"=>[#Jekyll:Post, #Jekyll:Post],
     "jekyll"=>[#Jekyll:Post]}
    

    site.categories['github issue'] 返回一个帖子数组 site.categories[0] 返回一个空数组

    为什么在标签后打印整个帖子内容?

    与上述{% for TAG in site.tags %} 中的原因相同,TAG 是一个散列,您看到的是这个散列的字符串表示形式。如果此标签中有两个帖子,则在打印 TAG 时会看到两个帖子。

    从这里获取标签名称:{{TAG.first}}

    为什么只打印一个标签?

    它打印两个标签

    Checking the i: 0
    Checking the tag: tag1
    THE WHOLE POST
    Checking the cat: (nothing is printed here)
    
    Checking the i: 0
    Checking the tag: 0
    Checking the cat: (nothing is printed here)
    

    这种行为显然是不可预测的,主要是因为您在_config.yml 中声明了标签和类别。您不应该这样做,因为 site.tagssite.categories 是由 Jekyll 在生成时根据您帖子中的标签和类别设置的。从您的配置中删除它,并且只在 default front matter config 或帖子中设置标签。

    为什么 i 在循环结束时不递增?

    {% assign i = i | plus: 1 %}
    

    liquid documentation

    可能的解决方案

    {% for tag in site.tags %}
      {% assign tagName = tag.first %}
      <h1>{{ tagName }}</h1>
        {% for category in site.categories %}
        <h2>{{ category.first }}</h2>
            {% for post in site.posts %}
              {% if post.tags contains tagName %}
                  <h3>{{ post.title }}</h3>
              {% endif %}
            {% endfor %}
        {% endfor %}
    {% endfor %}
    

    【讨论】:

    • 非常感谢!您的回答确实消除了很多困惑。所以看起来“TAG in site.tags”的行为与site.tags.TAG 相同?也就是说,它返回TAG 下的一组帖子?此外,在您的解决方案中,帖子中的循环与类别中的循环是分离的,因此对于每个标签,它会打印所有可用的类别,然后在相同标签的不同类别下打印相同的帖子。我只想要与标签关联的类别。 (在下一条评论中继续>>)
    • (
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多