【问题标题】:Flash-Messages in Symfony2 doesn't seem to work in my twig-templateSymfony2 中的 Flash-Messages 似乎在我的 twig-template 中不起作用
【发布时间】:2011-11-23 09:49:26
【问题描述】:

我想在我们的页面上添加对 Flash 消息的支持。我实施了 遵循找到的文档here

我在基本布局中添加了以下代码片段。 (我也尝试添加 它到一个特定的动作模板)。

{% if app.session.hasFlash('notice') %} 
    <div id="flashmessage" class="flash-notice"> 
       {{ app.session.flash('notice') }} 
   </div> 
{% endif %} 

添加后抛出以下错误

Twig_Error_Runtime:第 66 行的“MyBundle::layout.html.twig”中不存在“”的项目“hasFlash”

我还有什么需要做的吗?

【问题讨论】:

  • var_dump($this-&gt;get('session')); 在您的控制器操作中输出什么?
  • 运行 2.0 的 symfony 我使用 hasFlash() 在你的例子中或 {% for flashMessage in app.session.getFlashes() %} {{ {{ flashMessage }} {% endfor %}

标签: templates symfony twig flash-message


【解决方案1】:

你使用 symfony 2.0 还是 2.1 (目前是 master 分支)

对于 symfony 2.1,文档位于:http://symfony.com/doc/2.1/book/controller.html#flash-messages

flash 消息显示如下:

{% for flashMessage in app.session.flashbag.get('notice') %}
    <div class="flash-notice">
        {{ flashMessage }}
    </div>
{% endfor %}

【讨论】:

    【解决方案2】:

    嗯,检查你的配置文件,你已经自动启动了会话:

    session:
        default_locale: %locale%
        auto_start:     true
    

    因为错误似乎是 Twig 没有找到会话类,而不是 hasFlash 函数。事实上,我的布局中的代码几乎完全相同。

    【讨论】:

    • 我同意这一点。在 Twig 模板中,app.session 似乎为空。
    【解决方案3】:

    在撰写本文时,这已经很老了,所以假设您现在已经解决了,但为了参考,它是 has 而不是 hasFlash。所以..

    {% if app.session.flashbag.has('notice') %} 
        <div id="flashmessage" class="flash-notice"> 
           {{ app.session.flashbag.get('notice') }} 
       </div> 
    {% endif %} 
    

    【讨论】:

    • 不起作用 (2.6) 因为 flashbag.get 返回一个数组。见手册。
    【解决方案4】:

    通过 symfony 2.6 +

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

    因为 flashbag 是这个版本的数组,所以你需要 foreach 或者使用 index.我正在使用索引,因为我不需要更多的东西。

    【讨论】:

      【解决方案5】:

      在控制器中

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

      在你的 Twig 文件中

      {% for flashMessage in app.session.flashbag.get('notice') %}
          <div class="alert alert-warning">{{ flashMessage }}</div>
      {% endfor %}  
      

      【讨论】:

        【解决方案6】:

        我只是发现如果intercept_redirects 在调试模式下为真,则闪存消息不起作用。

        【讨论】:

          【解决方案7】:

          您是否在操作中的某处设置了 Flash 消息?

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

          请记住,flash 消息将存储在用户的会话中,仅用于一个额外请求。

          【讨论】:

          • 如果你正确阅读问题,app.session在twig模板中不存在,与设置无关
          猜你喜欢
          • 1970-01-01
          • 2013-10-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多