Symfony 如何防止此代码重复细枝

Symfony 如何防止此代码重复细枝,symfony,twig,Symfony,Twig,我在模板的很大一部分中使用了这段代码: {% if app.session.hasFlash('error') %} <div class="error"> {{ app.session.flash('error') }} </div> {% endif %} {%if-app.session.hasFlash('error')%} {{app.session.flash('error')} {%endif%}

我在模板的很大一部分中使用了这段代码:

{% if app.session.hasFlash('error') %}
        <div class="error">
            {{ app.session.flash('error') }}
        </div>
{% endif %}
{%if-app.session.hasFlash('error')%}
{{app.session.flash('error')}
{%endif%}
但是错误这个词正在改变。你能告诉我如何避免代码重复吗


使用include或macro,我只能更改div类,但是app.session.flash中的单词error怎么办?这样做有意义吗,或者最好还是不这样做?

您可以在“with”选项中包含这一点。例如:

{% include 'AcmeDemoBundle:Tools:flash.html.twig' with {'flash':'error'} %}
然后在flash.html.twig中执行以下操作:

{% if app.session.hasFlash(flash) %}
        <div class="{{flash}}">
            {{ app.session.flash(flash) }}
        </div>
{% endif %}
{%if app.session.hasFlash(flash)%}
{{app.session.flash(flash)}
{%endif%}