The Templating Component
Warning: You are browsing the documentation for Symfony 3.x, which is no longer maintained.
Read the updated version of this page for Symfony 7.1 (the current stable version).
The Templating component provides all the tools needed to build any kind of template system.
It provides an infrastructure to load template files and optionally monitor them for changes. It also provides a concrete template engine implementation using PHP with additional tools for escaping and separating templates into blocks and layouts.
Installation
1
$ composer require symfony/templating:^3.4
Note
If you install this component outside of a Symfony application, you must
require the vendor/autoload.php
file in your code to enable the class
autoloading mechanism provided by Composer. Read
this article for more details.
Usage
See also
This article explains how to use the Templating features as an independent component in any PHP application. Read the Creating and Using Templates article to learn about how to work with templates in Symfony applications.
The PhpEngine class is the entry point of the component. It needs a template name parser (TemplateNameParserInterface) to convert a template name to a template reference (TemplateReferenceInterface). It also needs a template loader (LoaderInterface) which uses the template reference to actually find and load the template:
1 2 3 4 5 6 7 8 9
use Symfony\Component\Templating\Loader\FilesystemLoader;
use Symfony\Component\Templating\PhpEngine;
use Symfony\Component\Templating\TemplateNameParser;
$filesystemLoader = new FilesystemLoader(__DIR__.'/views/%name%');
$templating = new PhpEngine(new TemplateNameParser(), $filesystemLoader);
echo $templating->render('hello.php', ['firstname' => 'Fabien']);
1 2
<!-- views/hello.php -->
Hello, <?= $firstname ?>!
The render() method parses
the views/hello.php
file and returns the output text. The second argument
of render
is an array of variables to use in the template. In this
example, the result will be Hello, Fabien!
.
Note
Templates will be cached in the memory of the engine. This means that if you render the same template multiple times in the same request, the template will only be loaded once from the file system.
The $view
Variable
In all templates parsed by the PhpEngine
, you get access to a mysterious
variable called $view
. That variable holds the current PhpEngine
instance. That means you get access to a bunch of methods that make your life
easier.
Including Templates
The best way to share a snippet of template code is to create a template that
can then be included by other templates. As the $view
variable is an
instance of PhpEngine
, you can use the render()
method (which was used
to render the template originally) inside the template to render another template:
1 2 3 4
<?php $names = ['Fabien', ...] ?>
<?php foreach ($names as $name) : ?>
<?= $view->render('hello.php', ['firstname' => $name]) ?>
<?php endforeach ?>
Global Variables
Sometimes, you need to set a variable which is available in all templates
rendered by an engine (like the $app
variable when using the Symfony
Framework). These variables can be set by using the
addGlobal() method and they
can be accessed in the template as normal variables:
1
$templating->addGlobal('ga_tracking', 'UA-xxxxx-x');
In a template:
1
<p>The google tracking code is: <?= $ga_tracking ?></p>
Caution
The global variables cannot be called this
or view
, since they are
already used by the PHP engine.
Note
The global variables can be overridden by a local variable in the template with the same name.
Output Escaping
When you render variables, you should probably escape them so that HTML or JavaScript code isn't written out to your page. This will prevent things like XSS attacks. To do this, use the escape() method:
1
<?= $view->escape($firstname) ?>
By default, the escape()
method assumes that the variable is outputted
within an HTML context. The second argument lets you change the context. For
example, to output something inside JavaScript, use the js
context:
1
<?= $view->escape($var, 'js') ?>
The component comes with an HTML and JS escaper. You can register your own escaper using the setEscaper() method:
1 2 3 4 5
$templating->setEscaper('css', function ($value) {
// ... all CSS escaping
return $escapedValue;
});
Helpers
The Templating component can be extended via helpers. Helpers are PHP objects that provide features useful in a template context. The component has one built-in helper:
Before you can use these helpers, you need to register them using set():
1 2 3 4
use Symfony\Component\Templating\Helper\SlotsHelper;
// ...
$templating->set(new SlotsHelper());
Custom Helpers
You can create your own helpers by creating a class which implements HelperInterface. However, most of the time you'll extend Helper.
The Helper
has one required method:
getName().
This is the name that is used to get the helper from the $view
object.
Creating a Custom Engine
Besides providing a PHP templating engine, you can also create your own engine using the Templating component. To do that, create a new class which implements the EngineInterface. This requires 3 method:
- render($name, array $parameters = []) - Renders a template
- exists($name) - Checks if the template exists
- supports($name) - Checks if the given template can be handled by this engine.
Using Multiple Engines
It is possible to use multiple engines at the same time using the DelegatingEngine class. This class takes a list of engines and acts just like a normal templating engine. The only difference is that it delegates the calls to one of the other engines. To choose which one to use for the template, the EngineInterface::supports() method is used:
1 2 3 4 5 6 7 8
use Acme\Templating\CustomEngine;
use Symfony\Component\Templating\DelegatingEngine;
use Symfony\Component\Templating\PhpEngine;
$templating = new DelegatingEngine([
new PhpEngine(...),
new CustomEngine(...),
]);
Learn More
- Slots Helper
- Creating and Using Templates
- How to Use PHP instead of Twig for Templates
- How to Access the User, Request, Session & more in Twig via the app Variable
- How to Dump Debug Information in Twig Templates
- How to Embed Controllers in a Template
- How to Escape Output in Templates
- How to Work with Different Output Formats in Templates
- How to Inject Variables into all Templates (i.e. global Variables)
- How to Embed Asynchronous Content with HInclude
- How to Organize Your Twig Templates Using Inheritance
- How to Use and Register Namespaced Twig Paths
- How to Override Templates from Third-Party Bundles
- How to Render a Template without a custom Controller
- How to Check the Syntax of Your Twig Templates
- How to Write a custom Twig Extension