Last active
August 29, 2015 14:24
-
-
Save jasongabler/3b638ea767336075e2d3 to your computer and use it in GitHub Desktop.
A simple way to render Twig template from a string... ? Seems to work for me.
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
# This is pretty much pilfered from: http://twig.sensiolabs.org/doc/recipes.html#using-a-database-to-store-templates | |
# and then modified to use a given strings for templates instead of fetching from the database... even simpler! | |
# The loader as a component: | |
class TwigString implements \Twig_LoaderInterface { | |
public function getSource($name) | |
{ | |
// get from database | |
return $name; | |
} | |
public function isFresh($name, $time) | |
{ | |
// determine from database | |
return true; | |
} | |
public function getCacheKey($name) | |
{ | |
// check if exists | |
return 'twigStringService:' . $name; | |
} | |
public function render($string, $variables) { | |
$twig = new \Twig_Environment($this); | |
return $twig->render($string, $variables); | |
} | |
} | |
# And, using it in a controller: | |
public function indexAction(Request $request) { | |
... | |
// Spelled out... | |
$twigString = new TwigString(); | |
$template = 'Hello {{ name }}'; | |
$variables = array('name' => 'Jason'); | |
$rendered = $twigString->render($template, $variables); | |
// Or in one line... | |
$rendered = (new TwigString())->render('Hello {{ name }}', array('name' => 'Jason')); | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment