Render Twig macro from PHP? -


i'm migrating project old custom xml-based templating engine twig. in order ease transition thought might nice able render twig macros inside old engine new widgets can built using twig , ran in both places needed.

the way can think of doing generate twig source code looks this:

{% import 'macros.twig' m %} {{ m.widget(...) }} 

and crazy like

eval('?>'.$twig->compilesource($twig->getloader()->getsource($name), $name)); 

which seems slow, dangerous, , brittle. there better way tap twig api?

yes, render template, should use:

echo $twig->loadtemplate($name)->render($context); 

the loadtemplate compile twig source if not exist in cache.

the render method render template safely.

a macro method of compiled class (see compiled template link of fiddle: http://twigfiddle.com/orfp3d) can call macro outside quite easily, that's not recommended (as macro not take part of templateinterface)


Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -