when using a centralized folder for image linking like the learn page suggests, is it somehow possible to store the image path for “page.find('/images')” in a global twig variable?
right now I always have to set the image path on each template, like this: {% set images = page.find('/images) %}} { images.media['my-image.jpg'].html }}
That’s redundant…
My idea is to define the set images variable somewhere global, to use is in multiple templates without defining it each time.
Maybe this is possible by extending the twig_vars in my theme.php, but I’m not sure if that’s the right approach?
Setting a global var inside the base template was one of the first things I tried. Unfortunately it does not work.
According to this answer it’s not possible to do this template-wise, without passing the variable as an argument when including partials. (Dynamic global variable)
Extending twig_vars inside my theme.php does work in fact. I just had a look at how it’s done at Gravs’ default theme quark, but I don’t know how to get page.find('/images') to work inside the theme.php
It’s not as well documented and often requires experimenting to see how it actually works, but if you are comfortable digging around in the API docs and sometimes source code, you’ll find that most Grav Twig functions have a PHP equivalent. In fact, I think the Twig API simply calls the PHP API and is a subset of it.
OK, got it working!
My theme.php looks like this now:
<?php
namespace Grav\Theme;
use Grav\Common\Theme;
use Grav\Common\Grav;
class THEME_NAME extends Theme
{
public function onTwigInitialized() {
$grav = Grav::instance();
$grav['pages']->init(); // initializing pages to access them
$twig = $this->grav['twig'];
$imagePath = $grav['pages']->find('/images');
$globalVars = [
'images' => $imagePath,
];
$twig->twig_vars = array_merge($twig->twig_vars, $globalVars);
}
}
You just have to initialize Pages before you can use them, then you can use the find(string $url, bool $all=false) function from the pages API to get the images location.
After this, I just can use my custom global var images in every twig template file, like this: