Skip to content

Instantly share code, notes, and snippets.

@chx
Created March 26, 2012 22:56
Show Gist options
  • Save chx/2210421 to your computer and use it in GitHub Desktop.
Save chx/2210421 to your computer and use it in GitHub Desktop.
drupal_render - twig integration
<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/Twig/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
// Almost empty class, just swaps Twig_Node_Print objects to Drupal_Twig_Node_Print objects.
class Drupal_Twig_NodeVisitor implements Twig_NodeVisitorInterface {
function enterNode(Twig_NodeInterface $node, Twig_Environment $env) {
if ($node instanceof Twig_Node_Print) {
return new Drupal_Twig_Node_Print($node->getNode('expr'), $node->getLine(), $node->getNodeTag());
}
return $node;
}
function leaveNode(Twig_NodeInterface $node, Twig_Environment $env) {
return $node;
}
function getPriority() {
return 0;
}
}
// A copy of the class Twig_Node_Print with a minor change, see below.
class Drupal_Twig_Node_Print extends Twig_Node implements Twig_NodeOutputInterface {
public function __construct(Twig_Node_Expression $expr, $lineno, $tag = null)
{
parent::__construct(array('expr' => $expr), array(), $lineno, $tag);
}
/**
* Compiles the node to PHP.
*
* @param Twig_Compiler A Twig_Compiler instance
*/
public function compile(Twig_Compiler $compiler)
{
$compiler
->addDebugInfo($this)
// This was just ->write('echo') in Twig_Node_Print
->write('echo render(')
->subcompile($this->getNode('expr'))
->raw(");\n")
;
}
}
require_once DRUPAL_ROOT . '/core/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$loader = new Twig_Loader_Filesystem(DRUPAL_ROOT . '/templates');
$twig = new Twig_Environment($loader, array(
'cache' => DRUPAL_ROOT . '/compilation_cache',
));
// This is where the magic ties in.
$twig->addNodeVisitor(new Drupal_Twig_NodeVisitor);
$template = $twig->loadTemplate('index.html');
$build = node_view(node_load(1));
echo $template->render(array('build' => $build));
@chx
Copy link
Author

chx commented Mar 26, 2012

index.html was just {{ build }}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment