代码之家  ›  专栏  ›  技术社区  ›  vimuth

symfony 4 twig override默认变量

  •  0
  • vimuth  · 技术社区  · 6 年前

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

    这是我的控制器,

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

    它仍然运行头代码。如果有人能帮忙,那就太好了。

    2 回复  |  直到 6 年前
        1
  •  1
  •   DarkBee    6 年前

    这里的问题是 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;
    }
    

    default false

    {% if has_header is defined and has_header %}
    
        2
  •  0
  •   vimuth    6 年前

    不是实际的解决方案,但找到了解决方法,

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

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