Twig render as html

Twig

The flexible, fast, and secure
template engine for PHP

Table of Contents

  • Basics
  • Rendering Templates
  • Environment Options
  • Loaders
    • Compilation Cache
    • Built-in Loaders
    • Create your own Loader
    • Core Extension
    • Escaper Extension
    • Sandbox Extension
    • Profiler Extension
    • Optimizer Extension

    Questions & Feedback

    Found a typo or an error?
    Want to improve this document? Edit it.

    Need support or have a technical question?
    Ask support on Stack Overflow.

    License

    Twig for Developers

    This chapter describes the API to Twig and not the template language. It will be most useful as reference to those implementing the template interface to the application and not those who are creating Twig templates.

    Basics

    Twig uses a central object called the environment (of class \Twig\Environment ). Instances of this class are used to store the configuration and extensions, and are used to load templates.

    Most applications create one \Twig\Environment object on application initialization and use that to load templates. In some cases, it might be useful to have multiple environments side by side, with different configurations.

    The typical way to configure Twig to load templates for an application looks roughly like this:

    require_once '/path/to/vendor/autoload.php'; $loader = new \Twig\Loader\FilesystemLoader('/path/to/templates'); $twig = new \Twig\Environment($loader, [ 'cache' => '/path/to/compilation_cache', ]);

    This creates a template environment with a default configuration and a loader that looks up templates in the /path/to/templates/ directory. Different loaders are available and you can also write your own if you want to load templates from a database or other resources.

    Notice that the second argument of the environment is an array of options. The cache option is a compilation cache directory, where Twig caches the compiled templates to avoid the parsing phase for sub-sequent requests. It is very different from the cache you might want to add for the evaluated templates. For such a need, you can use any available PHP cache library.

    Rendering Templates

    To load a template from a Twig environment, call the load() method which returns a \Twig\TemplateWrapper instance:

    $template = $twig->load('index.html');

    Before Twig 1.28, use loadTemplate() instead which returns a \Twig\Template instance.

    To render the template with some variables, call the render() method:

    echo $template->render(['the' => 'variables', 'go' => 'here']);

    The display() method is a shortcut to output the rendered template.

    You can also load and render the template in one fell swoop:

    echo $twig->render('index.html', ['the' => 'variables', 'go' => 'here']);

    The possibility to render blocks from the API was added in Twig 1.28.

    If a template defines blocks, they can be rendered individually via the renderBlock() call:

    echo $template->renderBlock('block_name', ['the' => 'variables', 'go' => 'here']);

    Environment Options

    When creating a new \Twig\Environment instance, you can pass an array of options as the constructor second argument:

    $twig = new \Twig\Environment($loader, ['debug' => true]);

    The following options are available:

    • debug boolean When set to true , the generated templates have a __toString() method that you can use to display the generated nodes (default to false ).
    • charset string (defaults to utf-8 ) The charset used by the templates.
    • base_template_class string (defaults to \Twig\Template ) The base template class to use for generated templates.
    • cache string or false An absolute path where to store the compiled templates, or false to disable caching (which is the default).
    • auto_reload boolean When developing with Twig, it’s useful to recompile the template whenever the source code changes. If you don’t provide a value for the auto_reload option, it will be determined automatically based on the debug value.
    • strict_variables boolean If set to false , Twig will silently ignore invalid variables (variables and or attributes/methods that do not exist) and replace them with a null value. When set to true , Twig throws an exception instead (default to false ).
    • autoescape string or boolean If set to true , HTML auto-escaping will be enabled by default for all templates (default to true ). As of Twig 1.8, you can set the escaping strategy to use ( html , js , false to disable). As of Twig 1.9, you can set the escaping strategy to use ( css , url , html_attr , or a PHP callback that takes the template name and must return the escaping strategy to use — the callback cannot be a function name to avoid collision with built-in escaping strategies). As of Twig 1.17, the filename escaping strategy (renamed to name as of Twig 1.27) determines the escaping strategy to use for a template based on the template filename extension (this strategy does not incur any overhead at runtime as auto-escaping is done at compilation time.)
    • optimizations integer A flag that indicates which optimizations to apply (default to -1 — all optimizations are enabled; set it to 0 to disable).

    Loaders

    Loaders are responsible for loading templates from a resource such as the file system.

    Compilation Cache

    All template loaders can cache the compiled templates on the filesystem for future reuse. It speeds up Twig a lot as templates are only compiled once.

    Built-in Loaders

    Here is a list of the built-in loaders:

    \Twig\Loader\FilesystemLoader

    The prependPath() and support for namespaces were added in Twig 1.10.

    Relative paths support was added in Twig 1.27.

    \Twig\Loader\FilesystemLoader loads templates from the file system. This loader can find templates in folders on the file system and is the preferred way to load them:

    $loader = new \Twig\Loader\FilesystemLoader($templateDir);

    It can also look for templates in an array of directories:

    $loader = new \Twig\Loader\FilesystemLoader([$templateDir1, $templateDir2]);

    With such a configuration, Twig will first look for templates in $templateDir1 and if they do not exist, it will fallback to look for them in the $templateDir2 .

    You can add or prepend paths via the addPath() and prependPath() methods:

    $loader->addPath($templateDir3); $loader->prependPath($templateDir4);

    The filesystem loader also supports namespaced templates. This allows to group your templates under different namespaces which have their own template paths.

    When using the setPaths() , addPath() , and prependPath() methods, specify the namespace as the second argument (when not specified, these methods act on the «main» namespace):

    $loader->addPath($templateDir, 'admin');

    Namespaced templates can be accessed via the special @namespace_name/template_path notation:

    \Twig\Loader\FilesystemLoader support absolute and relative paths. Using relative paths is preferred as it makes the cache keys independent of the project root directory (for instance, it allows warming the cache from a build server where the directory might be different from the one used on production servers):

    $loader = new \Twig\Loader\FilesystemLoader('templates', getcwd().'/..');

    When not passing the root path as a second argument, Twig uses getcwd() for relative paths.

    \Twig\Loader\ArrayLoader

    \Twig\Loader\ArrayLoader loads a template from a PHP array. It is passed an array of strings bound to template names:

    $loader = new \Twig\Loader\ArrayLoader([ 'index.html' => 'Hello >!', ]); $twig = new \Twig\Environment($loader); echo $twig->render('index.html', ['name' => 'Fabien']);

    This loader is very useful for unit testing. It can also be used for small projects where storing all templates in a single PHP file might make sense.

    When using the Array loaders with a cache mechanism, you should know that a new cache key is generated each time a template content «changes» (the cache key being the source code of the template). If you don’t want to see your cache grows out of control, you need to take care of clearing the old cache file by yourself.

    \Twig\Loader\ChainLoader

    \Twig\Loader\ChainLoader delegates the loading of templates to other loaders:

    $loader1 = new \Twig\Loader\ArrayLoader([ 'base.html' => '', ]); $loader2 = new \Twig\Loader\ArrayLoader([ 'index.html' => 'Hello >', 'base.html' => 'Will never be loaded', ]); $loader = new \Twig\Loader\ChainLoader([$loader1, $loader2]); $twig = new \Twig\Environment($loader);

    When looking for a template, Twig tries each loader in turn and returns as soon as the template is found. When rendering the index.html template from the above example, Twig will load it with $loader2 but the base.html template will be loaded from $loader1 .

    You can also add loaders via the addLoader() method.

    Create your own Loader

    All loaders implement the \Twig\Loader\LoaderInterface :

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
    interface Twig_LoaderInterface < /** * Gets the source code of a template, given its name. * * @param string $name string The name of the template to load * * @return string The template source code * * @deprecated since 1.27 (to be removed in 2.0), implement \Twig\Loader\SourceContextLoaderInterface */ function getSource($name); /** * Gets the cache key to use for the cache for a given template name. * * @param string $name string The name of the template to load * * @return string The cache key */ function getCacheKey($name); /** * Returns true if the template is still fresh. * * @param string $name The template name * @param timestamp $time The last modification time of the cached template */ function isFresh($name, $time); >

    The isFresh() method must return true if the current cached template is still fresh, given the last modification time, or false otherwise.

    As of Twig 1.27, you should also implement \Twig\Loader\SourceContextLoaderInterface to avoid deprecation notices.

    As of Twig 1.11.0, you can also implement \Twig\Loader\ExistsLoaderInterface to make your loader faster when used with the chain loader.

    Using Extensions

    Twig extensions are packages that add new features to Twig. Register an extension via the addExtension() method:

    $twig->addExtension(new \Twig\Extension\SandboxExtension());

    Twig comes bundled with the following extensions:

    • TwigExtensionCoreExtension: Defines all the core features of Twig.
    • TwigExtensionDebugExtension: Defines the dump function to help debug template variables.
    • TwigExtensionEscaperExtension: Adds automatic output-escaping and the possibility to escape/unescape blocks of code.
    • TwigExtensionSandboxExtension: Adds a sandbox mode to the default Twig environment, making it safe to evaluate untrusted code.
    • TwigExtensionProfilerExtension: Enables the built-in Twig profiler (as of Twig 1.18).
    • TwigExtensionOptimizerExtension: Optimizes the node tree before compilation.
    • TwigExtensionStringLoaderExtension: Defines the template_from_string function to allow loading templates from string in a template.

    The Core, Escaper, and Optimizer extensions are registered by default.

    Built-in Extensions

    This section describes the features added by the built-in extensions.

    Read the chapter about extending Twig to learn how to create your own extensions.

    Core Extension

    The core extension defines all the core features of Twig:

    Escaper Extension

    The escaper extension adds automatic output escaping to Twig. It defines a tag, autoescape , and a filter, raw .

    When creating the escaper extension, you can switch on or off the global output escaping strategy:

    $escaper = new \Twig\Extension\EscaperExtension('html'); $twig->addExtension($escaper);

    If set to html , all variables in templates are escaped (using the html escaping strategy), except those using the raw filter:

    You can also change the escaping mode locally by using the autoescape tag (see the autoescape doc for the syntax used before Twig 1.8):

    autoescape 'html' %> > raw >> escape >> endautoescape %>

    The autoescape tag has no effect on included files.

    The escaping rules are implemented as follows:

      Literals (integers, booleans, arrays, . ) used in the template directly as variables or filter arguments are never automatically escaped:

    " : "
    Twig" >>
    set text = "Twig
    " %>
    Twig" >> Twig" >> set text = "Twig
    " %>
    raw : "
    Twig" >>

    Источник

    Читайте также:  Error during session start please check your php
Оцените статью