Skip to content

Instantly share code, notes, and snippets.

@ijy
Forked from patcoll/twig.php
Created December 29, 2011 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ijy/1533834 to your computer and use it in GitHub Desktop.
Save ijy/1533834 to your computer and use it in GitHub Desktop.
Command-line script to process YAML frontmatter with Twig templates.
<?php
/**
* twig.php
*
* Command-line script to process YAML frontmatter with Twig templates.
* Inspired by Mustache <http://github.com/defunkt/mustache>.
*
* Example template file (test.html):
* ---
* people: [ {name: scott}, {name: laura} ]
* ---
* {% for person in people %}
* Hi {{ person.name }}!
* {% endfor %}
*
* Usage:
* cat test.html | php twig.php
*
* Or use "cat" to concatenate separate files together.
*
* Example YAML file (test.yml):
* ---
* people: [ {name: scott}, {name: laura} ]
* ---
*
* Example template file (test.html):
* {% for person in people %}
* Hi {{ person.name }}!
* {% endfor %}
*
* Usage:
* cat test.yml test.html | php twig.php
*
*/
require_once 'sfYaml.php';
require_once 'Twig/Autoloader.php';
Twig_Autoloader::register();
$text = array_map('trim', file('php://stdin'));
$edges = array_keys($text, '---');
if (count($edges) < 2) {
echo "YAML frontmatter must start and end with '---'. Example:\n";
echo "---\n";
echo "name: John\n";
echo "---\n";
echo "\n";
exit(1);
}
$last_edge = end($edges);
$frontmatters = array();
for ($i=0; $i < count($edges)-1; $i++) {
$frontmatters[] = implode("\n", array_slice($text, $edges[$i] + 1, ($edges[$i+1] - $edges[$i] - 1))) . "\n";
}
$template_text = implode("\n", array_slice($text, $last_edge + 1)) . "\n";
$loader = new Twig_Loader_String();
$twig = new Twig_Environment($loader);
foreach ($frontmatters as $frontmatter) {
$template = $twig->loadTemplate($template_text);
$data = sfYaml::load($frontmatter);
if (empty($data)) {
continue;
}
$template->display($data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment