简体   繁体   English

从PHP渲染Twig宏?

[英]Render Twig macro from PHP?

I'm currently migrating a project from an old custom XML-based templating engine to Twig . 我目前正在将一个项目从旧的基于XML的定制模板引擎迁移到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. 为了简化过渡,我认为能够从旧引擎内部渲染Twig宏可能会很好,以便可以使用Twig构建新的小部件并根据需要在两个地方运行。

The only way I can think of doing it is to generate some Twig source code that looks like this: 我能想到的唯一方法是生成一些如下所示的Twig源代码:

{% 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? 是否有更好的方式利用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. 如果在缓存中不存在该树枝,则loadTemplate将编译该树枝源。

The render method will render your template safely. render方法将安全地渲染您的模板。

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 ) 宏基本上是编译类的一种方法(请参见此提琴的编译模板链接: http : //twigfiddle.com/orfp3d ),您可以从外部轻松地调用宏,但是不建议这样做(因为您的宏不会参加TemplateInterface

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM