繁体   English   中英

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

[英]Creating dynamic Twig template inside the PHP Controller with Symfony

解释我的需求:

  • 我希望我的用户使用 Google Docs 自己创建一个“树枝模板”
  • 例如,如果在我用户的 GDocs 中有 {% if user.id is 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 只是提供了一种搜索和替换字符串的方法(搜索“{% if user.id is defind %}{{ user.name }}{% endif % }”,替换为“约翰”)。

所以...

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

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

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

先感谢您 !

您可以在树枝中使用template_from_string()将字符串评估为树枝代码:

$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)) }}

文档中的更多信息

暂无
暂无

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

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