symfony 4 twig 覆盖默认变量 [英] symfony 4 twig override default variable

查看:39
本文介绍了symfony 4 twig 覆盖默认变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

{% if has_header|default(true) == true %}<!-- 标题代码-->{% 万一 %}

这是我的控制器,

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

但不幸的是,即使我添加了 将 'has_header' 添加到 false 它仍然运行标题代码.如果有人可以提供帮助,那就太好了.

解决方案

这里的问题是 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('变量has_header"不存在.', 2, $this->source); })()), true)) : (true))== 真)) {

如你所见,你的变量通过函数_twig_default_filter

function _twig_default_filter($value, $default = '') {如果 (twig_test_empty($value)) {返回 $default;}返回 $value;}

进一步阅读源代码,您会发现问题在于函数 twig_test_empty

function twig_test_empty($value) {if ($value instanceof Countable) {返回 0 == 计数($ 值);}返回 '​​' === $value ||false === $value ||null === $value ||数组() === $value;}

<小时>

TLDR Twig 的过滤器 default 也会在 false 上起作用要解决此问题,您需要将代码更改为

{% 如果定义了 has_header 并且 has_header %}

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.

解决方案

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 %}

这篇关于symfony 4 twig 覆盖默认变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆