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

Twig help: to test for YAML variable in META file

Started by Muut Archive 11 years ago · 2 replies · 485 views
11 years ago

I cant figure out how to test for the presence of a variable in an yaml meta file.

For example:
imageName.jpg is in the same folder as its meta file imageName.jpg.meta.yaml

The contents of imageName.jpg.meta.yaml are:

title: Image Name
media: acrylic
surface: canvas 36 x 36 inches
style: geometric abstract
portfolio: true
thumbnail: false

I can of course access those variables easily like this <div>{{ image.meta.media }}</div> but if media is not defined in the meta.yaml file, I expected something like this to work (usually using in a for loop):

{% if image.meta.media %}
<div>{{ image.meta.media }}</div>
{% endif %}

But that doesn't work, it always thinks image.meta.media exists in the meta.yaml file, and when it isn't defined the output in that <div> will be a really screwed up <img> tag.

As always, any help is much appreciated.

11 years ago

Your approach works fine for me, just tested. You might want to dump image.meta.media with {{dump(image.meta.media)}} to see what's its value

11 years ago

@ritchiedalto If nothing works, you may try accessing the meta media attribute a bit differently using the get method like

TWIG

{% if image.get('media') %}
  <div>{{ image.get('media') }}</div>
{% endif %}
---

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1345 9 years ago
Archive · by Muut Archive, 9 years ago
2 932 9 years ago
Archive · by Muut Archive, 9 years ago
2 4059 9 years ago
Archive · by Muut Archive, 9 years ago
1 2945 9 years ago
Archive · by Muut Archive, 9 years ago
3 1117 9 years ago