9951 explained code solutions for 126 technologies


twigHow to render a Twig template from a string using PHP?


Rendering a Twig template from a string using PHP is possible with the help of the Twig_Loader_String class. This class allows you to load a template from a string instead of a file.

// Create a Twig Loader
$loader = new Twig_Loader_String();

// Create a Twig Environment
$twig = new Twig_Environment($loader);

// Render a template
echo $twig->render('Hello {{ name }}!', array('name' => 'John Doe'));

Output example

Hello John Doe!

Code explanation

  • Twig_Loader_String: This class allows you to load a template from a string instead of a file.
  • Twig_Environment: This class is used to create a Twig Environment.
  • render: This method is used to render a template.

Helpful links

Edit this code on GitHub