【问题标题】:Jekyll Liquid Syntax, how to dereference a propertyJekyll Liquid 语法,如何取消引用属性
【发布时间】:2021-02-26 18:58:28
【问题描述】:

我正在使用这个液体标签对我网站上的帖子进行分组。

{% assign postsForYear = site.posts | group_by_exp:"post", "post.date | date: '%Y'" | where: "name", "2020" %} 

当我将postForYear 回显到屏幕时,我看到了:

{"name"=>"2020", "items"=>[#, #, #, #, #, #], "size"=>6} 0

这是有道理的,因为那一年我有六个帖子。但是,我试图取消引用该对象并获取 .size 属性,我可以在输出中看到它......我无法弄清楚语法!

如何获取 .Size 属性?

这些都不起作用。

{{ postsForYear.size }}
{{ postsForYear.items | size }}

在那之后,我很想学习如何通过帖子了解自己的方式...这看起来也很简单,但行不通!

【问题讨论】:

    标签: jekyll liquid


    【解决方案1】:

    啊,我想通了。奇怪的是,postsForYear 数组实际上被视为数组本身,所以我必须索引到第一个位置才能访问属性。

    {% assign postsForYear = site.posts | 
        group_by_exp:"post", "post.date | date: '%Y'" | where: "name", "2020" %} 
    
    ###doesn't work
    {{ postsForYear.items | size }}
    
    ### does work
    {{ postsForYear[0].items | size }}
    
    ### example
    Posts for year {{ postsForYear[0].name }}, total posts {{ postsForYear[0].size }} 
    
    >Posts for year 2020, total posts 6  
    

    然后回答我的另一个问题,如何解决问题:

    {% for post in postsForYear[0].items %}
       <h1>{{post.title}}</h1><br>
    {% endfor %}
    
    

    【讨论】:

    • 为了记录,数组是由group_by创建的,如文档中所示:jekyllrb.com/docs/liquid/filters/#group-by {{ site.members | group_by_exp: "item", "item.graduation_year | truncate: 3, ''" }} 会给出类似[{"name"=&gt;"201", "items"=&gt;[...]}, {"name"=&gt;"200", "items"=&gt;[...]}]的东西
    • 啊,有道理。谢谢!
    • 这表示我真的不明白你为什么要分组。你可以这样做:where: "post", "post.date | date: '%Y' == 2020"(或== '2020',可能是因为我希望日期返回一个字符串)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 2014-10-28
    相关资源
    最近更新 更多