Nope, because tpl::load is a toolkit function which doesn’t use the Template component (it’s the other way round: the Template component uses it for loading PHP templates). So the Twig plugin can’t (and shouldn’t) change it.
But the twig() helper function is fairly similar. So rendering the page programmatically might look like:
tpl::$data = array_merge(tpl::$data, [
'kirby' => kirby(),
'site' => site(),
'pages' => pages(),
'page' => $items_topic
], $items_topic->templateData());
echo twig('@templates/sometemplate.twig');
// or, same but a bit more verbose:
// echo Kirby\Twig\Plugin::render('@templates/sometemplate.twig');
Alternatively, I wonder if the route action could be simplified by just returning the page?
if ( isset($items_topic) && !empty($items_topic) ){
return $items_topic;
}
If you don’t need to override the page’s “natural” template, there should be no need to populate tpl:$data yourself and call tpl::load() or twig(), you can let Kirby render the page.
I’ve tried just the twig() helper function but I get the error “Call to undefined function twig()”. I also register the Twig Plugin first with Kirby\Twig\Plugin::register(); but than I get a 500 error.
The alternative solution by just returning the page is simple and would work. Thank you for that.
But anyway I want to know why I get these errors?!
Sorry! I have installed the older version of twig ^^. It works now. Thank you very much
I figure the error is because Kirby loads the config files first, then the plugins, so you end up trying to use plugin features before they’re defined. That’s a design flaw with Kirby routes, IMHO.
I suppose you used the classic installation method, rather than Composer?
If so, one workaround would be to load the plugin early, for instance in a site.php at the root of your project you could have:
<?php
$kirby = kirby();
// Load the Twig plugin early so we can use it in config files (e.g. for routes)
require_once $kirby->roots()->plugins() . '/twig/twig.php';
But I haven’t tried it and I’m not 100% sure it won’t mess up with Kirby’s initialization.
Wouldn’t an alternative be to define the route in a plugin? However, you would have to make sure that this plugin loads after the twig plugin (plugins are loaded in alphabetical order).
<?php
// site/plugins/my-routes.php
// load the Twig plugin if not yet loaded
$kirby->plugin('twig');
// register our routes
$kirby->set('route', [
'pattern' => '(:any)/(:any)/details/(:any)',
'action' => function($i18n, $section, $details) {
// do something here, and we should have access the the twig() function
// (or to Kirby\Twig\Plugin::render())
}
]);
I’m using the Kirby Registry syntax because I’m not sure if using c::set would work at this stage. Plus it’s a good way to add a route without overwriting existing routes config.