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

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

General

Getting item from List with specific title

Solved by Karmalakas View solution

Started by Jan 2 years ago · 6 replies · 84 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
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
2 years ago

thank you, this is exactly what I was looking for!

Suggested topics

Topic Participants Replies Views Activity
General · by Jerry Hunt, 4 days ago
2 80 9 hours ago
General · by pamtbaau, 14 hours ago
1 51 13 hours ago
General · by Andy Miller, 1 day ago
0 44 1 day ago
General · by Marcel, 12 months ago
6 346 5 days ago
General · by Duc , 5 days ago
3 40 5 days ago