Quick Twig Template Rendering Without Much Set Up


Sometimes, I want to prepare more readable output from my PHP scripts. It is good to create a template and render with values from script out put.

Here is a quick way to render a twig template. First lets assume the HTML twig template (test-report.html.twig) is:

<!doctype html>
<html lang="en">
  <head>
    <title>My script output</title>
  </head>
  <body>

  <div>
    <div><b>Name: </b>{{ name }}</div>
    <div><b>Pace: </b>{{ place }}</div>
  </div>
  </body>
</html>

Then we have this script, test-script.php:

<?php

$loader = new \Twig\Loader\FilesystemLoader([getcwd()]);
$twig = new \Twig\Environment($loader);
$file_handle = fopen('test-report.html', 'w');
fwrite($file_handle, $twig->render('test-report.html.twig', ['name' => 'Junaid', 'place' => 'Kannur']));
fclose($file_handle);

Keeping above two files in same place and running the script. We will get output, test-report.html:

<!doctype html>
<html lang="en">
  <head>
    <title>My script output</title>
  </head>
  <body>

  <div>
    <div><b>Name: </b>Junaid</div>
    <div><b>Pace: </b>Kannur</div>
  </div>
  </body>
</html>


Leave a Reply

Your email address will not be published.