How to Use PHP instead of Twig for Templates

How to Use PHP instead of Twig for Templates

Deprecated since version 4.3: PHP templates have been deprecated in Symfony 4.3 and they will no longer be supported in Symfony 5.0. Use Twig templates instead.

Symfony defaults to Twig for its template engine, but you can still use plain PHP code if you want. Both templating engines are supported equally in Symfony. Symfony adds some nice features on top of PHP to make writing templates with PHP more powerful.

Tip

If you choose not use Twig and you disable it, you’ll need to implement your own exception handler via the kernel.exception event.

Rendering PHP Templates

If you want to use the PHP templating engine, first install the templating component:

  1. $ composer require symfony/templating

Deprecated since version 4.3: The integration of the Templating component in FrameworkBundle has been deprecated since version 4.3 and will be removed in 5.0.

Next, enable the PHP engine:

  • YAML

    1. # config/packages/framework.yaml
    2. framework:
    3. # ...
    4. templating:
    5. engines: ['twig', 'php']
  • XML

    1. <!-- config/packages/framework.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony
    9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    10. <framework:config>
    11. <!-- ... -->
    12. <framework:templating>
    13. <framework:engine id="twig"/>
    14. <framework:engine id="php"/>
    15. </framework:templating>
    16. </framework:config>
    17. </container>
  • PHP

    1. // config/packages/framework.php
    2. $container->loadFromExtension('framework', [
    3. // ...
    4. 'templating' => [
    5. 'engines' => ['twig', 'php'],
    6. ],
    7. ]);

You can now render a PHP template instead of a Twig one by using the .php extension in the template name instead of .twig. The controller below renders the index.html.php template:

  1. // src/Controller/HelloController.php
  2. // ...
  3. public function index($name)
  4. {
  5. // template is stored in src/Resources/views/hello/index.html.php
  6. return $this->render('hello/index.html.php', [
  7. 'name' => $name
  8. ]);
  9. }

Caution

Enabling the php and twig template engines simultaneously is allowed, but it will produce an undesirable side effect in your application: the @ notation for Twig namespaces will no longer be supported for the render() method:

  1. public function index()
  2. {
  3. // ...
  4. // namespaced templates will no longer work in controllers
  5. $this->render('@SomeNamespace/hello/index.html.twig');
  6. // you must use the traditional template notation
  7. $this->render('hello/index.html.twig');
  8. }
  1. {# inside a Twig template, namespaced templates work as expected #}
  2. {{ include('@SomeNamespace/hello/index.html.twig') }}
  3. {# traditional template notation will also work #}
  4. {{ include('hello/index.html.twig') }}

Decorating Templates

More often than not, templates in a project share common elements, like the well-known header and footer. In Symfony, this problem is thought about differently: a template can be decorated by another one.

The index.html.php template is decorated by layout.html.php, thanks to the extend() call:

  1. <!-- src/Resources/views/hello/index.html.php -->
  2. <?php $view->extend('layout.html.php') ?>
  3. Hello <?= $name ?>!

Now, have a look at the layout.html.php file:

  1. <!-- src/Resources/views/layout.html.php -->
  2. <?php $view->extend('base.html.php') ?>
  3. <h1>Hello Application</h1>
  4. <?php $view['slots']->output('_content') ?>

The layout is itself decorated by another one (base.html.php). Symfony supports multiple decoration levels: a layout can itself be decorated by another one:

  1. <!-- src/Resources/views/base.html.php -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  6. <title><?php $view['slots']->output('title', 'Hello Application') ?></title>
  7. </head>
  8. <body>
  9. <?php $view['slots']->output('_content') ?>
  10. </body>
  11. </html>

For both layouts, the $view['slots']->output('_content') expression is replaced by the content of the child template, index.html.php and layout.html.php respectively (more on slots in the next section).

As you can see, Symfony provides methods on a mysterious $view object. In a template, the $view variable is always available and refers to a special object that provides a bunch of methods that makes the template engine tick.

Working with Slots

A slot is a snippet of code, defined in a template, and reusable in any layout decorating the template. In the index.html.php template, define a title slot:

  1. <!-- src/Resources/views/hello/index.html.php -->
  2. <?php $view->extend('layout.html.php') ?>
  3. <?php $view['slots']->set('title', 'Hello World Application') ?>
  4. Hello <?= $name ?>!

The base layout already has the code to output the title in the header:

  1. <!-- src/Resources/views/base.html.php -->
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  4. <title><?php $view['slots']->output('title', 'Hello Application') ?></title>
  5. </head>

The output() method inserts the content of a slot and optionally takes a default value if the slot is not defined. And _content is a special slot that contains the rendered child template.

For large slots, there is also an extended syntax:

  1. <?php $view['slots']->start('title') ?>
  2. Some large amount of HTML
  3. <?php $view['slots']->stop() ?>

Including other Templates

The best way to share a snippet of template code is to define a template that can then be included into other templates.

Create a hello.html.php template:

  1. <!-- src/Resources/views/hello/hello.html.php -->
  2. Hello <?= $name ?>!

And change the index.html.php template to include it:

  1. <!-- src/Resources/views/hello/index.html.php -->
  2. <?php $view->extend('layout.html.php') ?>
  3. <?= $view->render('hello/hello.html.php', ['name' => $name]) ?>

The render() method evaluates and returns the content of another template (this is the exact same method as the one used in the controller).

Embedding other Controllers

And what if you want to embed the result of another controller in a template? That’s very useful when working with Ajax, or when the embedded template needs some variable not available in the main template.

If you create a fancy action, and want to include it into the index.html.php template, use the following code:

  1. <!-- src/Resources/views/hello/index.html.php -->
  2. <?= $view['actions']->render(
  3. new \Symfony\Component\HttpKernel\Controller\ControllerReference(
  4. 'App\Controller\HelloController::fancy',
  5. [
  6. 'name' => $name,
  7. 'color' => 'green',
  8. ]
  9. )
  10. ) ?>

But where is the $view['actions'] array element defined? Like $view['slots'], it’s called a template helper, and the next section tells you more about those.

Using Template Helpers

The Symfony templating system can be extended via helpers. Helpers are PHP objects that provide features useful in a template context. actions and slots are two of the built-in Symfony helpers.

Speaking of web applications, creating links between pages is a must. Instead of hardcoding URLs in templates, the router helper knows how to generate URLs based on the routing configuration. That way, all your URLs can be updated by changing the configuration:

  1. <a href="<?= $view['router']->path('hello', ['name' => 'Thomas']) ?>">
  2. Greet Thomas!
  3. </a>

The path() method takes the route name and an array of parameters as arguments. The route name is the main key under which routes are referenced and the parameters are the values of the placeholders defined in the route pattern:

  1. # config/routes.yaml
  2. hello:
  3. path: /hello/{name}
  4. controller: App\Controller\HelloController::index

Using Assets: Images, JavaScripts and Stylesheets

What would the Internet be without images, JavaScripts, and stylesheets? Symfony provides the assets tag to deal with them:

  1. <link href="<?= $view['assets']->getUrl('css/blog.css') ?>" rel="stylesheet" type="text/css"/>
  2. <img src="<?= $view['assets']->getUrl('images/logo.png') ?>"/>

The assets helper’s main purpose is to make your application more portable. Thanks to this helper, you can move the application root directory anywhere under your web root directory without changing anything in your template’s code.

Profiling Templates

By using the stopwatch helper, you are able to time parts of your template and display it on the timeline of the WebProfilerBundle:

  1. <?php $view['stopwatch']->start('foo') ?>
  2. ... things that get timed
  3. <?php $view['stopwatch']->stop('foo') ?>

Tip

If you use the same name more than once in your template, the times are grouped on the same line in the timeline.

Output Escaping

When using PHP templates, escape variables whenever they are displayed to the user:

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

By default, the escape() method assumes that the variable is outputted within an HTML context. The second argument lets you change the context. For instance, to output something in a JavaScript script, use the js context:

  1. <?= $view->escape($var, 'js') ?>

Form Theming in PHP

When using PHP as a templating engine, the only method to customize a fragment is to create a new template file - this is similar to the second method used by Twig.

The template file must be named after the fragment. You must create a integer_widget.html.php file in order to customize the integer_widget fragment.

  1. <!-- src/Resources/integer_widget.html.php -->
  2. <div class="integer_widget">
  3. <?= $view['form']->block(
  4. $form,
  5. 'form_widget_simple',
  6. ['type' => isset($type) ? $type : "number"]
  7. ) ?>
  8. </div>

Now that you’ve created the customized form template, you need to tell Symfony to use it. Inside the template where you’re actually rendering your form, tell Symfony to use the theme via the setTheme() helper method:

  1. <?php $view['form']->setTheme($form, [':form']) ?>
  2. <?php $view['form']->widget($form['age']) ?>

When the form.age widget is rendered, Symfony will use the customized integer_widget.html.php template and the input tag will be wrapped in the div element.

If you want to apply a theme to a specific child form, pass it to the setTheme() method:

  1. <?php $view['form']->setTheme($form['child'], ':form') ?>

Note

The :form syntax is based on the functional names for templates: Bundle:Directory. As the form directory lives in the templates/ directory, the Bundle part is empty, resulting in :form.

Making Application-wide Customizations

If you’d like a certain form customization to be global to your application, you can accomplish this by making the form customizations in an external template and then importing it inside your application configuration.

By using the following configuration, any customized form fragments inside the templates/form folder will be used globally when a form is rendered.

  • YAML

    1. # config/packages/framework.yaml
    2. framework:
    3. templating:
    4. form:
    5. resources:
    6. - 'App:Form'
    7. # ...
  • XML

    1. <!-- config/packages/framework.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony
    9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    10. <framework:config>
    11. <framework:templating>
    12. <framework:form>
    13. <framework:resource>App:Form</framework:resource>
    14. </framework:form>
    15. </framework:templating>
    16. <!-- ... -->
    17. </framework:config>
    18. </container>
  • PHP

    1. // config/packages/framework.php
    2. // PHP
    3. $container->loadFromExtension('framework', [
    4. 'templating' => [
    5. 'form' => [
    6. 'resources' => [
    7. 'App:Form',
    8. ],
    9. ],
    10. ],
    11. // ...
    12. ]);

By default, the PHP engine uses a div layout when rendering forms. Some people, however, may prefer to render forms in a table layout. Use the FrameworkBundle:FormTable resource to use such a layout:

  • YAML

    1. # config/packages/framework.yaml
    2. framework:
    3. templating:
    4. form:
    5. resources:
    6. - 'FrameworkBundle:FormTable'
  • XML

    1. <!-- config/packages/framework.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony
    9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    10. <framework:config>
    11. <framework:templating>
    12. <framework:form>
    13. <resource>FrameworkBundle:FormTable</resource>
    14. </framework:form>
    15. </framework:templating>
    16. <!-- ... -->
    17. </framework:config>
    18. </container>
  • PHP

    1. // config/packages/framework.php
    2. $container->loadFromExtension('framework', [
    3. 'templating' => [
    4. 'form' => [
    5. 'resources' => [
    6. 'FrameworkBundle:FormTable',
    7. ],
    8. ],
    9. ],
    10. // ...
    11. ]);

If you only want to make the change in one template, add the following line to your template file rather than adding the template as a resource:

  1. <?php $view['form']->setTheme($form, ['FrameworkBundle:FormTable']) ?>

Note that the $form variable in the above code is the form view variable that you passed to your template.

Adding a “Required” Asterisk to Field Labels

If you want to denote all of your required fields with a required asterisk (*), you can do this by customizing the form_label fragment.

When using PHP as a templating engine you have to copy the content from the original template:

  1. <!-- form_label.html.php -->
  2. <!-- original content -->
  3. <?php if ($required) { $label_attr['class'] = trim((isset($label_attr['class']) ? $label_attr['class'] : '').' required'); } ?>
  4. <?php if (!$compound) { $label_attr['for'] = $id; } ?>
  5. <?php if (!$label) { $label = $view['form']->humanize($name); } ?>
  6. <label <?php foreach ($label_attr as $k => $v) { printf('%s="%s" ', $view->escape($k), $view->escape($v)); } ?>><?= $view->escape($view['translator']->trans($label, $label_translation_parameters, $translation_domain)) ?></label>
  7. <!-- customization -->
  8. <?php if ($required) : ?>
  9. <span class="required" title="This field is required">*</span>
  10. <?php endif ?>

Adding “help” Messages

You can also customize your form widgets to have an optional “help” message.

When using PHP as a templating engine you have to copy the content from the original template:

  1. <!-- form_widget_simple.html.php -->
  2. <!-- Original content -->
  3. <input
  4. type="<?= isset($type) ? $view->escape($type) : 'text' ?>"
  5. <?php if (!empty($value)): ?>value="<?= $view->escape($value) ?>"<?php endif ?>
  6. <?= $view['form']->block($form, 'widget_attributes') ?>
  7. />
  8. <!-- Customization -->
  9. <?php if (isset($help)) : ?>
  10. <span class="help"><?= $view->escape($help) ?></span>
  11. <?php endif ?>

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.