Symfony 如何访问base.html.twig中的peekAll()以检查消息/闪烁
在symfony 4.1中 在控制器中:Symfony 如何访问base.html.twig中的peekAll()以检查消息/闪烁,symfony,twig,Symfony,Twig,在symfony 4.1中 在控制器中: $this->addFlash( 'notice', 'Your changes were saved!' ); return $this->render(...); 细枝基模板: {% for message in app.flashes('notice') %} <div class="flash-notice"> {{ message }} </div> {%
$this->addFlash(
'notice',
'Your changes were saved!'
);
return $this->render(...);
细枝基模板:
{% for message in app.flashes('notice') %}
<div class="flash-notice">
{{ message }}
</div>
{% endfor %}
{%用于app.flash中的消息('notice')%}
{{message}}
{%endfor%}
这很好,但我想将所有消息包装在一个div中。以下操作不起作用:
{% if app.flashes is not empty %}
<div id="messageBox" class="overlay">
<div class="message" onclick="slide(document.querySelector('#messageBox')); this.classList.add('fadeAway');">
{% for label, messages in app.flashes %}
<section class="{{ label }}">
<p><b>{{ label }}</b></p>
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
</section>
{% endfor %}
</div>
</div>
{% endif %}
{%如果app.flash不是空的%}
{%用于标签,app.flash%中的消息}
{{label}}
{消息%中的消息为%s}
- {{message}}
{%endfor%}
{%endfor%}
{%endif%}
问题是行{%if app.flash不是空的%}
会删除消息,因此下面的for循环和空结果
如何将
peekAll()
用于if
逻辑?我不知道这是否是最好的方法,但以下是我的解决方案
在base.html.twig中:
{% set flashes = app.flashes %}
{% if flashes is not empty %}
<div id="messageBox" class="overlay">
<div class="message" onclick="slide(document.querySelector('#messageBox')); this.classList.add('fadeAway');">
{% for label, messages in flashes %}
<section class="{{ label }}">
<p><b>{{ label }}</b></p>
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
</section>
{% endfor %}
</div>
</div>
{% endif %}
{%set flash=app.flash%}
{%如果闪烁不是空的%}
{%用于标签,消息以快闪%}
{{label}}
{消息%中的消息为%s}
- {{message}}
{%endfor%}
{%endfor%}
{%endif%}
基本上,将
app.flash的返回值设置为flash
,并进行处理。检查peekAll()
的正确方法是{%if-app.session.flashbag.peekAll()不是空的%}
这不会按照文档中的说明清除flashBag。访问app.flash的行为似乎会将其从flash集中删除。也许你可以在评估它们之前将它们检索到一个非易失性的本地结构中。也许这篇博文可以帮助你(如果你使用symfony>3.2)(查看for循环的最后一部分)检查{%if app.session.flashbag.all is not empty%}
也有同样的效果-我会坚持我的答案,因为现在找到了答案