Skip to content

Instantly share code, notes, and snippets.

@EvanLovely
Last active January 25, 2018 07:21
Show Gist options
  • Save EvanLovely/165329dc361ff07b669e3ca365ec5ffe to your computer and use it in GitHub Desktop.
Save EvanLovely/165329dc361ff07b669e3ca365ec5ffe to your computer and use it in GitHub Desktop.
Twig PHP CLI Render
composer init
composer require twig/twig

Usage

echo '{"title": "hello there"}' | php index.php '@upone/bar.twig'`
<?php
require_once 'vendor/autoload.php';
// Twig docs for this: https://twig.symfony.com/doc/2.x/api.html
// First arg to CLI - template path
$templatePath = $argv[1];
// data is STDIN aka `echo '{"title": "hello there"}' | php index.php '@upone/bar.twig'`
$in_data = [];
$in = fgets(STDIN);
if ($in) {
$in_data = json_decode($in, true);
}
// Creates Twig Loader, uses `./templates` as default directory to look for Twig files
$loader = new Twig_Loader_Filesystem('templates');
// Add as many Twig Namespaces as you'd like
$loader->addPath(getcwd() . '/..', 'upone');
// Create Twig Environment with the `$loader` just made and some global settings
$twig = new Twig_Environment($loader, [
'debug' => true,
]);
// Load the template that was first arg to this script
$template = $twig->load($templatePath);
// Pass data to template and get back HTML
$html = $template->render($in_data);
echo $html;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment