Skip to main content

Template Engine

The second main feature of Simply is the use of the Twig template engine via the class TemplateEngine.

note

The template engine is a lazy service so you can inject it without asking any questions about performance.

Render a template​

Inject Simply\Core\Template\TemplateEngine (or get the public framework.template_engine service):

use Simply\Core\Template\TemplateEngine;

class ProjectCard
{
public function __construct(private TemplateEngine $templates)
{
}

public function display(object $project): void
{
// Prints the template; pass false as third argument to get it as a string
$this->templates->render('project/card.html.twig', ['project' => $project]);
}
}

getEngine() returns the Twig Environment.

Templates are searched in the views/ directory of the registered theme, and in the directories added with the simply/config/view_directories filter (see below).

With WP_DEBUG false, compiled templates are cached in the Simply cache. With WP_DEBUG true, there is no cache and the Twig dump() function is available.

Documentation​

All the documentation for twig is available here. Read it carefully to understand how to use it in the framework.

Custom functions added to twig​

fn/function​

To call specific function into twig template you can use fn or function twig function. Here an example to call comments_template function.

<div class="comments">
{{ fn('comments_template') }}
</div>

And another example with parameters :

<a href="{{ fn('get_author_posts_url', aPost.post.post_author) }}">
...
</a>

Add custom twig configuration​

You can add custom functions or globals with the simply/config/template filter :

add_filter('simply/config/template', function (\Twig\Environment $twig) {
$twig->addFunction(new \Twig\TwigFunction('isLive', ThemeSettings::class . '::isLive'));
$twig->addGlobal('theme', new ThemeUtils());
return $twig;
});

Register custom views directories​

To tell Twig where search template files you have to use simply/config/view_directories filter :

add_filter('simply/config/view_directories', function(array $viewsDirectory) {
$viewsDirectory[] = realpath(__DIR__ . '/views');
return $viewsDirectory;
});