I'm currently migrating a project from an old custom XML-based templating engine to Twig . In order to ease the transition I thought it might be nice to be able to render Twig macros from inside the old engine so that new widgets can be built using Twig and be ran in both places as needed.
The only way I can think of doing it is to generate some Twig source code that looks like this:
{% import 'macros.twig' as m %}
{{ m.widget(...) }}
And then do something crazy like
eval('?>'.$twig->compileSource($twig->getLoader()->getSource($name), $name));
Which seems slow, dangerous, and brittle. Is there a better way to tap into the Twig API?
Yes, to render a template, you should use:
echo $twig->loadTemplate($name)->render($context);
The loadTemplate
will compile the twig source if it does not exist in cache.
The render
method will render your template safely.
A macro is basically a method of the compiled class (see the compiled template link of this fiddle: http://twigfiddle.com/orfp3d ) you can call a macro from outside quite easily, but that's not recommended (as your macro will not take part of the TemplateInterface
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.