The Templating Component

The Templating component provides all the tools needed to build any kindof template system.

It provides an infrastructure to load template files and optionallymonitor them for changes. It also provides a concrete template engineimplementation using PHP with additional tools for escaping and separatingtemplates into blocks and layouts.

Installation

  1. $ composer require symfony/templating

Note

If you install this component outside of a Symfony application, you mustrequire the vendor/autoload.php file in your code to enable the classautoloading mechanism provided by Composer. Readthis article for more details.

Usage

This article explains how to use the Templating features as an independentcomponent in any PHP application. Read the article about templatesto learn about how to work with templates in Symfony applications.

The PhpEngine class is the entry pointof the component. It needs atemplate name parser (TemplateNameParserInterface)to convert a template name to atemplate reference (TemplateReferenceInterface).It also needs a template loader (LoaderInterface)which uses the template reference to actually find and load the template:

  1. use Symfony\Component\Templating\Loader\FilesystemLoader;
  2. use Symfony\Component\Templating\PhpEngine;
  3. use Symfony\Component\Templating\TemplateNameParser;
  4.  
  5. $filesystemLoader = new FilesystemLoader(__DIR__.'/views/%name%');
  6.  
  7. $templating = new PhpEngine(new TemplateNameParser(), $filesystemLoader);
  8.  
  9. echo $templating->render('hello.php', ['firstname' => 'Fabien']);

  1. <!-- views/hello.php -->
  2. Hello, <?= $firstname ?>!

The render() method parsesthe views/hello.php file and returns the output text. The second argumentof render is an array of variables to use in the template. In thisexample, the result will be Hello, Fabien!.

Note

Templates will be cached in the memory of the engine. This means that ifyou render the same template multiple times in the same request, thetemplate will only be loaded once from the file system.

The $view Variable

In all templates parsed by the PhpEngine, you get access to a mysteriousvariable called $view. That variable holds the current PhpEngineinstance. That means you get access to a bunch of methods that make your lifeeasier.

Including Templates

The best way to share a snippet of template code is to create a template thatcan then be included by other templates. As the $view variable is aninstance of PhpEngine, you can use the render() method (which was usedto render the template originally) inside the template to render another template:

  1. <?php $names = ['Fabien', ...] ?>
  2. <?php foreach ($names as $name) : ?>
  3. <?= $view->render('hello.php', ['firstname' => $name]) ?>
  4. <?php endforeach ?>

Global Variables

Sometimes, you need to set a variable which is available in all templatesrendered by an engine (like the $app variable when using the SymfonyFramework). These variables can be set by using theaddGlobal() method and theycan 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 arealready used by the PHP engine.

Note

The global variables can be overridden by a local variable in the templatewith the same name.

Output Escaping

When you render variables, you should probably escape them so that HTML orJavaScript code isn't written out to your page. This will prevent things likeXSS attacks. To do this, use theescape() method:

  1. <?= $view->escape($firstname) ?>

By default, the escape() method assumes that the variable is outputtedwithin an HTML context. The second argument lets you change the context. Forexample, 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 ownescaper using thesetEscaper() method:

  1. $templating->setEscaper('css', function ($value) {
  2. // ... all CSS escaping
  3.  
  4. return $escapedValue;
  5. });

Helpers

The Templating component can be extended via helpers. Helpers are PHP objectsthat provide features useful in a template context. The component has onebuilt-in helper:

  1. use Symfony\Component\Templating\Helper\SlotsHelper;
  2. // ...
  3.  
  4. $templating->set(new SlotsHelper());

Custom Helpers

You can create your own helpers by creating a class which implementsHelperInterface. However,most of the time you'll extendHelper.

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 engineusing the Templating component. To do that, create a new class whichimplements the EngineInterface. Thisrequires 3 method:

Using Multiple Engines

It is possible to use multiple engines at the same time using theDelegatingEngine class. This classtakes a list of engines and acts just like a normal templating engine. Theonly difference is that it delegates the calls to one of the other engines. Tochoose which one to use for the template, theEngineInterface::supports()method is used:

  1. use Acme\Templating\CustomEngine;
  2. use Symfony\Component\Templating\DelegatingEngine;
  3. use Symfony\Component\Templating\PhpEngine;
  4.  
  5. $templating = new DelegatingEngine([
  6. new PhpEngine(...),
  7. new CustomEngine(...),
  8. ]);

Learn More