Templates

Last updated: Wed, 12 Sep 2018 09:48

In Berlioz, we recommend to use Twig template engine:

Integration in Berlioz

If you use the main repository of Berlioz : berlioz/berlioz, the package it's already available.

If you use customizable repositories, you need to install by yourself the TwigPackage.

Installation of Twig package

Use composer to install package:

composer require berlioz/twig-package

For more detail package installation, referred to the package description page.

Template service

Template engine in Berlioz implements the \Berlioz\Core\Package\TemplateEngine interface, who have some methods:

  • TemplateEngine::addGlobal(string $name, $value): TemplateEngine

    Add global variable.

  • TemplateEngine::registerPath(string $path, string $namespace = null)

    Register a new path for template engine.

  • TemplateEngine::render(string $name, array $variables = []): string

    Add global variable.

  • TemplateEngine::addGlobal(string $name, $value): TemplateEngine

    Render a template.

  • TemplateEngine::hasBlock(string $tplName, string $blockName): bool

    Has block in template?

  • TemplateEngine::renderBlock(string $tplName, string $blockName, array $variables = []): string

    Render a block in template.

Usage

In controllers, the method render(string $name, array $variables = []): string is available to process of the rendering of a template file.

Example inside controllers methods:

// In controller method
$rendering = $this->render('my-template/path/file.html.twig',
                           ['myVar' => 'value']);

Example outside controllers:

/** @var \Berlioz\Core\Package\TemplateEngine $templateEngine */
$templateEngine = $this->getApp()->getServiceContainer()->get('templating');
$rendering = $templateEngine->render('my-template/path/file.html.twig',
                                     ['myVar' => 'value']);