user702300
user702300

Reputation: 1241

PHP Silex Framework can't add Twig_Extension_StringLoader extension

I am trying to use template_from_string as stated on

http://twig.sensiolabs.org/doc/functions/template_from_string.html

How can I do that from Silex? I see that the Twig/Exteion/StringLoader.php file is there. Here is the code I've tried

$app['twig'] = $app->share($app->extend('twig', function($twig, $app) {
    $twig->addExtension(new MarkdownExtension());
    $twig->addExtension(new Twig_Extension_StringLoader());
    return $twig;
}));

But when I try to use it like

    return $app['twig']->template_from_string(
        "The is the {{ title }}", 
        array('title' => 'Hello')
    );

It generates following error

Fatal error: Call to undefined method Twig_Environment::template_from_string()

What I am trying to do is fetch the template content from DB or another file, then render it with Twig instead of using a template file, so I can combine several section templates into the main template. Or if there a better way?

Please note that I already know how to use insert within the template file like

{% include 'home-section.html.twig' %}

but this won't solve my problem because it can not fetch the content data to be parsed automatically.

Thank you.

Upvotes: 0

Views: 448

Answers (1)

user702300
user702300

Reputation: 1241

Just had to create another twig object

$loader = new Twig_Loader_String();
$twig = new Twig_Environment($loader);

echo $twig->render('Hello {{ name }}!', array('name' => 'Fabien'));

Upvotes: 0

Related Questions