twig - 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它仍然运行标头代码。如果有人可以提供帮助,那就太好了。
解决方案
这里的问题是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 %}
推荐阅读
- windows-10 - 为 Windows 10(1803 及更高版本)创建自定义触摸键盘布局
- python - 如何使用熊猫替换所有列中的所有字符串?
- python - 猜谜游戏isdigit帮助python
- php - 移除特定的 URL 参数
- angular - Firefox 中的 Twilio 视频大小调整
- python - 如何在 Tensorflow 中进行联合推理
- laravel - Laravel 铸造指数浮动不起作用
- java - Java Socket连接在没有调用关闭连接的情况下关闭
- api - Laravel API 输出中的包装器
- swift - 验证来自 macOS 应用扩展的收据?