amteich / kirby-twig

Twig templating support for Kirby CMS
MIT License
48 stars 12 forks source link

Global Kirby objects should be added to the environment as globals #35

Closed MoritzLost closed 1 year ago

MoritzLost commented 1 year ago

The Twig page template receives variables in the $twig->render() call, which means they're available in the template. If I dump the context, I can see the global objects:

{# default.twig #}
{{ dump(_context|keys) }}

This shows kirby, site, pages and page. However, if I include another template without context, those variables aren't available any more:

{# default.twig #}
{{ include('other-template.twig', with_context = false) }}

{# other-template.twig #}
{{ dump(_context|keys) }}

This only dumps an empty array, because no global variables are set.

Passing the global objects manually is tedious, those should be available in every template automatically. This can be accomplished by adding those objects to the Twig environment as globals. At least the four most prominently used objects – $kirby, $site, $pages, $page (if the current route has a page) – should be provided as globals:

$twig->addGlobal('kirby', $kirby);
$twig->addGlobal('site', $site);
$twig->addGlobal('pages', $pages);
$twig->addGlobal('page', $page);

There are probably some other global objects that should be provided as globals. For example: $user, $users, $session and $request.

seehat commented 1 year ago

I like the idea and added some important globals:

https://github.com/amteich/kirby-twig/releases/tag/4.2.0

MoritzLost commented 1 year ago

@seehat Great, thanks!

MoritzLost commented 1 year ago

@seehat We just tested the update, unfortunately it looks like the pages global is not working properly yet. It's just using the pages() helper, but that one does not return a collection with all pages (like the $pages variable you get per default in PHP templates). The helper expects an array of IDs and returns a collection with those IDs, so calling pages() without any arguments just returns an empty collection, which is not that useful.

I would prefer if the pages global variable contained a collection of all pages, like the $pages variable provided to PHP templates. I haven't found the place this variable is initialized yet, but looks like site()->index() should do the job?

seehat commented 1 year ago

Alright. I will look into this. Sry.

seehat commented 1 year ago

This should be fixed now on version 4.2.1

MoritzLost commented 1 year ago

@seehat Looks like it's working great now, thanks for the change!

seehat commented 1 year ago

Good to hear. :)