【问题标题】:Liquid + Jekyll, "unless" not working inside "for" loopLiquid + Jekyll,“除非”不在“for”循环内工作
【发布时间】:2015-12-30 00:11:41
【问题描述】:

给定一组页面,我正在制作 JSON。我想跳过任何没有标题的页面,最后一个元素后面不能有逗号,那是糟糕的 JSON。尝试了不同的变化,这里是一个例子:

---
---
[
{% for page in site.pages %}
    {% unless page.title %}
        {% continue %}
    {% else %}
{
"title":"{{ page.title }}",
"content":"{{ page.content | strip_html | strip_newlines }}",
"href":"{{ page.url }}"
}
    {% endunless %}
    {% unless forloop.last %},{% endunless %}
{% endfor %}
]

生成的 JSON 文件的结尾如下所示:

{
"title":"Test Search",
"content":" ",
"href":"/search.html"
}

    ,



]

如何去掉结尾的逗号?提前谢谢你。

【问题讨论】:

    标签: json for-loop jekyll liquid continue


    【解决方案1】:

    我认为您的问题是您的最后一个循环迭代没有标题。

    尝试添加逗号。这样您就不必展望未来:

    {% assign isFirst = true %}
    {% for page in site.pages %}
        {% unless page.title %}{% continue %}{% endunless %}
        {% unless isFirst %},{% endunless %}
        {% assign isFirst = false %}
        {
        "title": {{ page.title | jsonify  }},
        "content": {{ page.content | strip_html | strip_newlines | jsonify  }},
        "href": {{ page.url | jsonify  }}
        }
    {% endfor %}
    

    编辑:您还应该使用jsonify 过滤器来确保正确转义引号和其他字符。

    【讨论】:

    • 是的,你对最后一次循环迭代是正确的,我以为我已经在另一个变体中解决了这个问题,但我错了。但是您发布的代码没有添加逗号。让我尝试修复....
    • @user3213137 你的权利。出于某种原因,我决定将 assign 语句添加到除非(当然)不起作用的块中。我现在改了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 2023-03-16
    • 2018-01-26
    • 1970-01-01
    • 2018-11-05
    • 2018-12-14
    • 1970-01-01
    相关资源
    最近更新 更多