symfony 4 twig override default variable

好久不见. 提交于 2019-12-11 18:05:54

问题


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.



来源:https://stackoverflow.com/questions/50804088/symfony-4-twig-override-default-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!