The Puli Extension for Twig¶
Puli provides an extension for the Twig templating engine. With this extension, you can refer to template files through Puli paths:
echo $twig->render('/acme/blog/views/show.html.twig');
The extension also adds a resource_url()
function for generating URLs for
public resources:
<img src="{{ resource_url('/app/public/images/logo.png') }}" />
Installation¶
Important
Before you continue, install the Puli CLI and the Repository Component in your project.
Install the extension with Composer:
$ composer require puli/twig-extension:^1.0
Configuration¶
To activate the extension, create a new
PuliTemplateLoader
and register it with Twig.
The loader enables Twig to load templates through Puli paths:
use Puli\TwigExtension\PuliTemplateLoader;
$twig = new \Twig_Environment(new PuliTemplateLoader($repo));
The loader receives Puli’s ResourceRepository
as
only argument.
Next, create a new PuliExtension
and add it to
Twig. The extension adds the resource_url()
function and does a few more
tweaks to properly support Puli in Twig:
use Puli\TwigExtension\PuliExtension;
// The $urlGenerator is only needed if you use the resource_url() function
$twig->addExtension(new PuliExtension($repo, $urlGenerator));
Usage in Twig¶
Using Puli in Twig is straight-forward: Use Puli paths wherever you would usually use a file path. For example:
{% extends '/acme/blog/views/layout.html.twig' %}
{% block content %}
{# ... #}
{% endblock %}
Contrary to Twig’s default behavior, you can also refer to templates using relative paths:
{% extends 'layout.html.twig' %}
{% block content %}
{# ... #}
{% endblock %}
Resource URLs¶
You can generate URLs for public Puli resources with the resource_url()
function:
<img src="{{ resource_url('/app/public/images/logo.png') }}" />
The function accepts both absolute and relative paths:
<img src="{{ resource_url('../public/images/logo.png') }}" />
Note
The resource must have been published with the publish
command of the
Puli CLI, otherwise the URL generator will fail. See the
URL generator documentation for more
information.