Template Engine with Twig

After some testing I think to found the best way to integrate Twig engine with KirbyCMS and now I need suggestions, for a moment posting only the my idea without code.

The main idea is not enter inside Kirby (because if the dev team want add support for change the template engine they added already, for now not want) so before i used the site.php system for ignore the main template engine and loading twig instead but i think is horrible way, for this i think to use another approch, the snippets.

I create a single snippet file with inside all twig engine (composer autoload, twig loader, twig functions/filters and the template rendering) and loading for any templates.

Example for default.php:

<?php snippet('plugins/twig') ?>

From original template engine I added this variables inside twig object:

  • kirby
  • site
  • pages
  • page

From snippet you can pass plus data with data param:

<?php snippet('plugins/twig', ['data' => ['example' => 'Example data var']]) ?>

For my logic I added the possible to passing the template name for change the original structure of Kirby:

<?php snippet('plugins/twig', ['template' => 'another_template.twig']) ?>

The snippet use some options, I think the best way is post the code:

$defaults = [
    'cache_dir'     => ((isset($cache_dir))     ? $cache_dir        : c::get('twig.cache_dir', $kirby->roots()->cache() . DS . 'twig')),
    'templates_dir' => ((isset($templates_dir)) ? $templates_dir    : c::get('twig.templates_dir', $kirby->roots()->templates() . DS . 'twig')),
    'template'      => ((isset($template))      ? $template         : $page->template() . c::get('twig.templates_ext', '.twig'))

I have integrated with kirby cache (if the page is cachable twig not save the processed template), this is userfull when you not need to create anytimes the page.

With this is really good when you put ignore pages into the cache because twig save the processed page for max performance.

For a moment not release the code because i not found many people discussion for this.


1 Like

I like the idea!

Can you setup a repo? I would like to try out.

For a moment i create a simple gist with a basic informations about the snippet. You need to add twig into the root of your site, example i have vendor folder where exists site/content/etc folders. You can see into the code where i load the composer autoload file.

If you follow my example put this gist into /site/snippets/plugins/twig.php and all examples working fine.

The templates loaded from default from /site/templates/twig, you can edit with configuration key “twig.templates_dir”, check my code for more info.


thanks for sharing. :+1: