Skip to content
Grav 2.0 is officially stable. Read the announcement →
General

Getting item from List with specific title

Solved by Karmalakas View solution

Started by Jan 2 years ago · 6 replies · 197 views
2 years ago

I have a list field called "contentblocks" with two elements: A text field called "title" and an editor field called "content".
So now in my Twig code I want to get the entry where the title is "youtube". I tried like this:
{{ page.header.contentblocks[title='YouTube'].content}}

that does not work. What can I do?

2 years ago

Can you post the code for the .md file of the page that contains the list of contentblocks?

2 years ago
YAML
contentblocks:
    -
        title: '**What if your strings had the perfect partner?**'
        content: "my content"
    -
        title: '## Tempera ROSIN in a nutshell:'
        content: "my content 2"
 -
        title: 'YouTube'
        content: "my YouTube link"
2 years ago Solution

List field is an array, so you should do an array search by value. Direct access would be something like:

TWIG
{{ page.header.contentblocks[0].content}}
{{ page.header.contentblocks[1].content}}

This will print the content of the first matching element:

TWIG
{{ page.header.contentblocks|filter(item => item.title == "YouTube")|first.content }}
👍 2
1 reply
2 years ago

You could use something like this:

TWIG
{% for item in page.header.contentblocks %}
  {% if item.title == 'YouTube' %} 
     <strong>{{ item.title|raw }}</strong>
     < p>{{ item.content|raw }}</p>
  {% endif %}
{% endfor %} 
TXT

2 years ago

Within a loop it would still be better to use the filter IMHO:

TWIG
{% for item in page.header.contentblocks|filter(cb => cb.title == "YouTube" -%}
     <strong>{{ item.title|raw }}</strong>
     <p>{{ item.content|raw }}</p>
{% endfor %} 

This will print all items that have a "YouTube" title

👍 1

Suggested topics

Topic Participants Replies Views Activity
General · by Andy Miller, 2 days ago
0 73 2 days ago
General · by Veehem, 3 days ago
0 113 3 days ago
General · by milkboy, 4 days ago
0 113 4 days ago
General · by ian russell, 2 weeks ago
2 205 1 week ago
General · by pamtbaau, 1 month ago
2 462 2 weeks ago