使用Symfony在PHP控制器中创建动态Twig模板



解释我的需求:

  • 我希望我的用户自己创建一个带有谷歌文档的"树枝模板">
  • 例如,如果我用户的 GDocs 中有 {% 如果 user.id 是 defind
  • %}{{ user.name }}{% endif %}
  • 我想在我的控制器中获取此字符串("{% if user.id is defind %}{{ user.name }}{% endif %}"(
  • 然后检查是否可以解释这个特定的 Twig 字符串
  • 如果是,请获取该树枝字符串的实际值(假设"John"(
  • 然后,在我的用户的 GDocs 中,将"{% if user.id is defind %}{{ user.name }}{% endif %}"替换为"John">

我绝对需要获取最终值("John"(,因为 GDocs 只是给出了一种搜索和替换字符串的方法(搜索"{% 如果 user.id 是 defind %}{{ user.name }}{% endif %}",替换为"John"(。

所以。。。

对于我在他们的 GDoc 中找到的每个树枝字符串,我需要测试我是否可以找到这根树枝的值。

有没有办法在我的控制器中"创建"树枝,用这样的东西替换它的值?

$myTwig = new TwigTemplate("{% if user.id is defind %}{{ user.name }}{% endif %}");
$myUserName = $this->render($myTwig, array("user" => $user")

提前谢谢你!

你可以在 twig 中使用template_from_string()将字符串作为 twig代码进行评估:

$myTwig = "{% if user.id is defind %}{{ user.name }}{% endif %}";
// $template can be the base template in which you inject the code
$myUserName = $this->render($template, array('myTwig' => $myTwig, "user" => $user");

在视图中:

{{ include(template_from_string(myTwig)) }}

文档中的详细信息

最新更新