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.

Themes & Styling

Using PageMediaSelect Custom Field in Template

Started by Noelle 8 years ago · 4 replies · 755 views
8 years ago

I am attempting to use a custom pagemediaselect field I created in my page template.

The only problem is that the variable to output the field "{{p.header.lead_image}}" only outputs the file name of the media I select using the mediaselect field (ex: filename.jpg).

I thought maybe I could input THAT variable into this code to create the entire URL ( {{p.media['{{p.header.lead_image}}']}}, but that's not working (I'm guessing you can't use two variables together).

Could anyone point me in the right direction on how to remedy this?

Thanks!

8 years ago

I think I figured it out!

TWIG
{% set filename = p.header.lead_image %}
{{p.media[filename]}}

It worked, but is this method advisable?

8 years ago

Hi
Your solution is fine but your first attempt was the preferred option because its easier to read and maintain. You had the right idea just the wrong syntax.

Something like this will create the entire image tag and is also easier to use if you ever need to loop over a number of images to display them
{{ page.media.images[ header.lead_image ].html( header.image_title , header.image_alt, 'my_static_class') }}

If you want to use title and alt fields you could add new fields to your blueprint or set them as static (or blank) fields with ''.

8 years ago

Btw, just note that pagemediaselect is not used anymore and maintained, it is recommended to use instead the filepicker field.

8 years ago

oh man I didn't know that and I use pagemediaselect all over the place!

Suggested topics

Topic Participants Replies Views Activity
Themes & Styling · by Pedro M, 2 months ago
4 193 2 months ago
Themes & Styling · by Ian, 2 months ago
3 90 2 months ago
Themes & Styling · by Norbert, 2 years ago
11 449 3 months ago
Themes & Styling · by Lukáš Findeis, 3 months ago
0 43 3 months ago
Themes & Styling · by Sebadamus, 4 months ago
5 123 3 months ago