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

Displaying images in a page folder

Started by Michael 9 years ago · 4 replies · 4253 views
9 years ago

Hi. I'm pretty new to Grav and I'm trying to display a header image from a file upload in the admin panel in a template. The idea is to upload the image to a folder within the specific page folder (the one that contains the md file) and not a centralised image folder. This way all the content for that page is together if I need to move or delete articles in the future.

YAML:
header.background_image:
type: file
label: Photo image header
destination: 'self@/header_image'
multiple: false
accept:

  • image/*

TWIG:
{% for image in page.find('header_image').media.images %}
{{ image.url }}
{% endfor %}

This displays fine when I've linked to a folder relative the the user pages folder, but I can't seem to get it to work in the above example. Am I missing something?

Thanks.

9 years ago

Hey, Michael! Glad to hear you are trying out Grav!

What I would do in your situation is something like:

TWIG
<img src="{{ page.url }}/{{ page.header.imagename }}" />

and add imagename in page header including the file extension.

This is just a crude example of doing what you need to do, but there are much more ways to customize it to just your needs. What I experience to work great for me is to do the simplest method first, do a note of it and improve it when I have nothing more important to implement it. This is of course if you don't implement it on a high traffic website which requires more load freiendly methods,

Good luck and happy Graving!

last edited 09/06/17 by mikael
9 years ago

Thanks for the quick reply, but I can't see your example in the above post.

9 years ago

Sorry, I forgot to format it as code... My fault 😊

To explain what this does:
It takes the page URL and adds the filename which it gets from the page header.
So in frontmatter do:

YAML
---
title: Test title
imagename: testimage.jpg
---
9 years ago

Brilliant, thanks for this. After hours of looking I also found this (doesn't add to folder rather than targets the image directly from the admin upload:
{{ page.media[header.background_image|first.name] }}

Which I'm going to turn into this for a tasty background image:
{{ page.media[header.background_image|first.name].cropResize(2400, 1350).url }}

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