简体   繁体   中英

Liquid + Jekyll, “unless” not working inside “for” loop

I'm making JSON given a set of pages. I want to skip any pages without titles, and the last element can not have a comma after it, that's bad JSON. Tried different variations, here is an example:

---
---
[
{% 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 %}
]

The end of the resulting JSON file looks like this:

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

    ,



]

How do I get rid of the trailing comma? Thank you in advance.

I think your problem is that your last loop iteration is one that has no title.

Try to prepend the comma. That way you don't have to look in the future:

{% 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 %}

Edit: You should also use the jsonify filter to ensure proper escaping of quotes and other characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM