Flash-Messages in Symfony2 doesn't seem to work in my twig-template

后端 未结 7 1598
不知归路
不知归路 2021-01-02 05:31

I want to add support for flash messages on our pages. I implemented this by following the documentation found here.

I added the following snipplet to my base layou

相关标签:
7条回答
  • 2021-01-02 06:07

    Mmm check in your config file that you have auto-started the session:

    session:
        default_locale: %locale%
        auto_start:     true
    

    Because the error seems to be that Twig doesn't find the session class, not something about the hasFlash function. In fact I have almost exactly the same code in my layout.

    0 讨论(0)
  • 2021-01-02 06:08

    In controller

    $this->get('session')->getFlashBag()->add('notice', 'Your message!');
    

    In your Twig file

    {% for flashMessage in app.session.flashbag.get('notice') %}
        <div class="alert alert-warning">{{ flashMessage }}</div>
    {% endfor %}  
    
    0 讨论(0)
  • 2021-01-02 06:12

    This is pretty old at time of writing so imagine you've worked it out by now, but for reference sake, it's has rather than hasFlash. So..

    {% if app.session.flashbag.has('notice') %} 
        <div id="flashmessage" class="flash-notice"> 
           {{ app.session.flashbag.get('notice') }} 
       </div> 
    {% endif %} 
    
    0 讨论(0)
  • 2021-01-02 06:12

    I just figure out that flash messages are not working if intercept_redirects is true in debug mode.

    0 讨论(0)
  • 2021-01-02 06:15

    Did you set the flash message somewhere in your action?

    $this->get('session')->setFlash('notice', 'Your changes were saved!');
    

    Remember that flash messages will be stored on the user's session for exactly one additional request.

    0 讨论(0)
  • 2021-01-02 06:21

    By symfony 2.6 +

    {% if app.session.flashbag.has('notice') %}
        {{ app.session.flashbag.get('notice').0 }}<br/>
    {% endif %}
    

    Because flashbag is by this version array you need foreach it or use index. I m using index because i dont need something more.

    0 讨论(0)
提交回复
热议问题