Skip to content

Latest commit

 

History

History
91 lines (55 loc) · 2.21 KB

File metadata and controls

91 lines (55 loc) · 2.21 KB

render

.. versionadded:: 3.15

    The ``render`` function was added in Twig 3.15.

The render function returns the rendered content of a template:

{{ render('template.html') }}

Templates

Templates are loaded via the current Twig loader.

Templates can be a string or an expression evaluating to a string:

{{ render('template.html') }}
{{ render(template_var) }}

A template can also be an instance of \Twig\Template or a \Twig\TemplateWrapper:

$template = $twig->load('some_template.twig');
$twig->display('template.twig', ['template' => $template]);

// You can render it like this:
// {{ render(template) }}

When you set the ignore_missing flag, Twig will return an empty string if the template does not exist:

{{ render('sidebar.html', ignore_missing = true) }}

You can also provide a list of templates that are checked for existence. The first template that exists will be rendered:

{{ render(['page_detailed.html', 'page.html']) }}

If ignore_missing is set, it will fall back to rendering nothing if none of the templates exist, otherwise it will throw an exception.

Context

Rendered templates do not have access to the variables defined in the context, but you can pass some explicitly:

{# template.html will have access to the "name" variable #}

{{ render('template.html', { name: 'Fabien' }) }}

When passing a variable from the current context, you can use the following shortcut:

{{ render('template.html', { first_name, last_name }) }}

{# is equivalent to #}

{{ render('template.html', { first_name: first_name, last_name: last_name }) }}

Sandboxing

When rendering a template created by an end user, you should consider :doc:`sandboxing<../sandbox>` it:

{{ render('page.html', sandboxed: true) }}

Arguments

  • template: The template to render
  • variables: The variables to pass to the template
  • ignore_missing: Whether to ignore missing templates or not
  • sandboxed: Whether to sandbox the template or not