DroidOS
DroidOS

Reputation: 8890

Parsing and using list item content via Twig

I am experimenting with using Grav to create my next website. One of the things I would be able to do is to build a unordered list using data provided in Grav frontmatter from the Grav page that uses the template. Here is how I am trying to do this

---
sectionone:
     listitems: "['Benefit 1','Benefit 2','Benefit 3']"
---

and then in the template somehow do the following

{% block featurelist %}
<ul>
{% set items = {{page.header.sectionone.consumers.benefits|json_decode}} %}
{% for item in {{}} %}
<li>{{item}}</li>
{% endfor %}
</ul>
{% endblock %}

However, Twig does not like this and reports back an error along the lines of

Twig_Error_Syntax A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "punctuation" of value "{".

with the offending line being my {% set items = ... } statement. I am clearly doing something wrong here but I am a Twig newbie so I fail to see what that might be.

Upvotes: 1

Views: 1489

Answers (2)

DroidOS
DroidOS

Reputation: 8890

I figured this out eventually. Grav documentation is by and large very good. However, the documentation on page headers/frontmatter appears to be somewhat incomplete. There is no full description of the entire syntax that is understood by the frontmatter processor. In order to define an array in front matter all you need to do is the following

---
sectionone:
 benefits: 
    - 'Benefit 1'
    - 'Benefit 2'
    - ...
---

In essence the standard markdown syntax for an unordered list. Grav's twig processor appears to convert this to a PHP array - no parsing required!

Upvotes: 1

BENARD Patrick
BENARD Patrick

Reputation: 30975

{% block featurelist %}
<ul>
   {% set items = page.header.sectionone.consumers.benefits|json_decode %}
   {% for item in items %}
      <li>{{item}}</li>
   {% endfor %}
</ul>
{% endblock %}

Upvotes: 1

Related Questions