首页 > 解决方案 > symfony 4 twig 覆盖默认变量

问题描述

我在我的视图中设置了一个默认变量(Twig 模板)。但是当我尝试在控制器内部覆盖它时,它并没有发生。这是我的看法,

<div class="content-wrapper">
    {% if has_header|default(true) == true %}
         <!-- Header code -->
    {% endif %}
</div>

这是我的控制器,

return $this->render('index.html.twig', [
    'has_header' => false
]);

但不幸的是,即使我添加了已将“has_header”添加为 false它仍然运行标头代码。如果有人可以提供帮助,那就太好了。

标签: twigsymfony4

解决方案


这里的问题是twig编译你的代码如下:

if ((((array_key_exists("has_header", $context)) ? (_twig_default_filter((isset($context["has_header"]) || array_key_exists("has_header", $context) ? $context["has_header"] : (function () { throw new Twig_Error_Runtime('Variable "has_header" does not exist.', 2, $this->source); })()), true)) : (true)) == true)) {

如您所见,您的变量被传递给函数_twig_default_filter

function _twig_default_filter($value, $default = '') {
  if (twig_test_empty($value)) {
    return $default;
  }
  return $value;
}

进一步阅读源代码,您可以看到问题出在函数中twig_test_empty

function twig_test_empty($value) {
  if ($value instanceof Countable) {
    return 0 == count($value);
  }
  return '' === $value || false === $value || null === $value || array() === $value;
}

TLDR Twig 的过滤器default也启动了false 要解决此问题,您需要将代码更改为

{% if has_header is defined and has_header %}

推荐阅读