Alright, I'm resurrecting this cause I am running into a similar problem.
I want to be able to render a 'string' - retrieved from the database - with custom AND common variables.
I tried the above posted method by Kasimi, but that doesn't seem to parse a common variable like
U_INDEX
, it does however parse the custom variables. Moreover, when I have a
{{ lang('TOPIC') }}
in the string, it throws the following error:
Unknown "lang" function in "template" at line 35.
controller:
Code: Select all
$this->template->assign_vars(array(
'S_PAGE_HEADER' => $this->parse_template_from_db($page['page_header'], $template_variables),
));
Code: Select all
/**
* Private function to parse a 'template string' retreived from the databse
*
* @param string $template_string The template string from the database
* @param array $template_variables The template variables that need to be parsed
* @return string A rendered template output
* @access private
*/
private function parse_template_from_db($template_string, $template_variables)
{
/* Decode HTML Special characters: < into < et cetera. */
$template_string = htmlspecialchars_decode($template_string);
$twig = new \Twig_Environment(new \Twig_Loader_Array(array('template' => $template_string)));
/* Parse the template variables we gave them */
$content = $twig->render('template', $template_variables);
/* Need to decode HTML Special characters again, for assigned variables */
return htmlspecialchars_decode($content);
}
It feels like I am setting up a complete new twig environment, without the standard functions and variables.
And then
nicofuma's comment made me thinking - partially cause I don't understand it fully - but that it should be possible to do it easier.
The only thing I found was
$template->assign_display
, but this doesn't seem to do the trick.
Basically what I am looking for is to render a string (within PHP) retrieved from the db with common and custom variables and functions and then assign it to a template variable.