【问题标题】:Render a php variable inside a twig template在树枝模板中渲染一个 php 变量
【发布时间】:2018-09-26 13:13:48
【问题描述】:

我有一个这样的 php 变量:

$text = "Hello {{ name }}!";

我调用 $twig->render 并将变量“name”设置为 John Doe。

在我的树枝模板中,我使用自己的功能来显示文本:

{% block test %}
  My name is: {{name}}
  <h3>
    {{ d("text") }}
  </h3>
{% endblock %}

我只是将 {{name}} 放在我的模板中以演示结果。 Twig_Function "d" 只返回 $text,所以我得到:

My name is: John Doe
<h3>
  Hello {{ name }}!
</h3>

我的预期结果应该是:

My name is: John Doe
<h3>
  Hello John Doe!
</h3>

两者都应该被渲染:我的正常 {{name}} 和我的 {{name}} 放在 $text 中。所以基本上我希望 twig 的渲染引擎在将变量 $text 放入模板后渲染它。这可能吗?

【问题讨论】:

标签: php function variables twig render


【解决方案1】:

感谢@Patrick Q...我只需要在 template_from_string() 周围放置一个 include() 就可以按预期工作:

{% block test %}
  My name is: {{name}}
  <h3>
    {{ include(template_from_string(d("text"))) }}
  </h3>
{% endblock %}

这里有一个解释:https://twig.symfony.com/doc/2.x/functions/template_from_string.html

【讨论】:

  • 顺便说一句:知道有人可以将这个include(template_from_string(d("text"))) 带入一个类似myfunction("text") 的函数中吗?
  • 为我上面的问题找到了解决方案:宏!在宏内部使用(全局)模板变量的方式在这里描述:stackoverflow.com/questions/15107760/…
猜你喜欢
  • 1970-01-01
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
  • 2011-11-11
  • 1970-01-01
相关资源
最近更新 更多