symfony 4 twig override default variable

2019-08-27 00:15发布

问题:

I have set a default variable in my view (Twig template). But when I try to override it inside controller it is not happening. This is my view,

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

This is my controller,

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

But unfortunately even I added the has added 'has_header' to false it still runs header code. It would be great if someone can help.

回答1:

The problem here is that twig compiles your code as follows:

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)) {

As you can see, your variable is passed down the function _twig_default_filter

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

Reading further in the source you can see the problem lays in the function 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's filter default also kicks in on false To solve this issue u would need to change your code to

{% if has_header is defined and has_header %}


回答2:

Not the actual solution but found a workaround for that,,,

TWIG

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

Controller

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

using strings instead of booleans is not the correct way but think it's simpler.



标签: twig symfony4