Created
March 2, 2010 15:53
-
-
Save patcoll/319596 to your computer and use it in GitHub Desktop.
Command-line script to process YAML frontmatter with Twig templates.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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
Is this a production-ready way to support YAML data in Twig templates or just more of a concept? I'd be really interested in finding a way to add YAML support to my templates.