picocms / Pico

Pico is a stupidly simple, blazing fast, flat file CMS.
http://picocms.org/
MIT License
3.81k stars 616 forks source link

Print metatdata Array #637

Closed ctuxboy closed 2 years ago

ctuxboy commented 2 years ago

Hello (again) :grin: ,

Trying print an array in my twig-file, but very strange it didn't show the array :confused:

Looking at some themes how they shows an array, but didn't work here.

Yaml:

links:
  - name: website-1.be
    url: https://website-1.be
  - name: website-2.be
    url: https://website-2.be

Twig:

{% for name, url in meta.links %}
  <p><a href="{{ url }}">{{ name }}</a></p>
{% endfor %}

Output:

Array

When adding quotes:

links:
  - name: 'website-1.be'
    url: 'https://website-1.be'
  - name: 'website-2.be'
    url: 'https://website-2.be'

Output:

0 1

So, it not shows the metadata variables in the array.

ctuxboy commented 2 years ago

Found it!

{% for item in meta.links %}
  <p><a href="{{ item.url }}">{{ item.name }}</a></p>
{% endfor %}

Item is the index! :smiley:

mayamcdougall commented 2 years ago

Glad you figured it out. 👍🏻

You can sometimes use the syntax you had first... it's just used for something different: key/value pairs.

You might see code like {% for key, value in meta.items %}.

If you were iterating over this data:

items:
  name: 'website-1.be'
  url: 'https://website-1.be'

Then on the first loop, {{ key }} would be name and {{ value }} would be website-1.be. Then on the next loop, {{ key }} would be url and {{ value }} would be https://website-1.be.

So, this syntax doesn't do what you wanted it to. 😉

It's only useful if you specifically need code that prints out the name of each key as you go.

ctuxboy commented 2 years ago

@mayamcdougall aha okay, now i understand :smiley: It was a littje confused when looking at Pico-themes using this for-loop methods, but yes, i figured out :smiley: