Liquid + Jekyll,"unless" 无法在 "for" 循环内工作
Liquid + Jekyll, "unless" not working inside "for" loop
我正在 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"
}
,
]
如何去掉结尾的逗号?提前谢谢你。
我认为你的问题是你的最后一个循环迭代没有标题。
尝试在前面加上逗号。这样你就不用再看未来了:
{% 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
过滤器以确保正确转义引号和其他字符。
我正在 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"
}
,
]
如何去掉结尾的逗号?提前谢谢你。
我认为你的问题是你的最后一个循环迭代没有标题。
尝试在前面加上逗号。这样你就不用再看未来了:
{% 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
过滤器以确保正确转义引号和其他字符。