amteich / kirby-twig

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

Site not available inside of a block template #20

Closed sonicpunk closed 2 years ago

sonicpunk commented 3 years ago

When accessing the site object within a twig template for a block element, I get the following error.

Error: Twig\Error\RuntimeError, line 2 of @templates/blocks/bloglink.twig

{% set page = site.find(block.linkselect) %} {% set pagetitle = page.title %} ➡ Variable "site" does not exist.

The value block.linkselect is the page.id. My goal is to retrieve the page object so that I can have access to all page object fields for my markup.

Of course I need there to be a site variable available at this level. Or am I going about it wrong?

sonicpunk commented 3 years ago

In our config we are exposing twig for use in block rendering so:

// Exposing functions etc to twig can be done here: // @see https://github.com/amteich/kirby-twig/blob/master/doc/functions.md 'mgfagency.twig.env.functions' => [ '*renderBlock' => function (string $name, array $args = []) { // Render a block by twig template, if available if (file_exists(dirname(__DIR__) . '/templates/blocks/' . $name . '.twig')) { return twig('@templates/blocks/' . $name . '.twig', $args); } // otherwise fallback to standard snippet template (php) return snippet('blocks/' . $name, $args, true); }, ],

Is it possible to send $site in with $args to get access to it on the block level?

seehat commented 3 years ago

I will look into it. In the meantime the site() function should work instead of $site.

sonicpunk commented 3 years ago

I am able to use a block php snippet for the output for the moment, but it would be nice to use one output language across the entire site.

seehat commented 3 years ago

Yes you can send $site to it. I think this should work: (not tested)

<?php 
'mgfagency.twig.env.functions' => [ '*renderBlock' => function (string $name, array $args = []) { 
    // Render a block by twig template, if available 
    if (file_exists(dirname(__DIR__) . '/templates/blocks/' . $name . '.twig')) { 
        $args['site'] = site();
        return twig('@templates/blocks/' . $name . '.twig', $args); } // otherwise fallback to standard snippet template (php) 
        return snippet('blocks/' . $name, $args, true); 
    }, 
],
seehat commented 3 years ago

@sonicpunk Did you have time to try the snippet?

seehat commented 2 years ago

Closing this because of long time of inactivity.