14

我需要使用 Silex 中的消息将一个页面重定向到另一个页面。希望有一种 Laravelesque 的方式,但我非常怀疑:

$app->redirect('/here', 301)->with('message', 'text');

然后我想在我的模板中显示消息:

{{ message }}

如果没有,还有其他方法吗?

更新

我看到getFlashBagSymfony 中有一个方法——那是我应该使用的吗?具体来说,我正在使用 Bolt 内容管理系统。

4

2 回答 2

32

是的,FlashBag 是正确的方法。在你的控制器中设置一个 flash 消息(你可以添加多个消息):

$app['session']->getFlashBag()->add('message', 'text');
$app->redirect('/here', 301)

并在模板中打印:

{% for message in app.session.getFlashBag.get('message') %}
    {{ message }}
{% endfor %}
于 2013-09-30T15:34:37.060 回答
5

我创建了这个FlashBagTrait可能有用的简单方法:

<?php
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;

trait FlashBagTrait
{
    /**
     * @return FlashBagInterface
     */
    public function getFlashBag() {
        return $this['session']->getFlashBag();
    }
}

只需将其添加到您的Application课程中,它就会使事情变得更加容易!

$app->getFlashBag()->add('message',array('type'=>"danger",'content'=>"You shouldn't be here"));

{% if app.flashbag.peek('message') %}
<div class="row">
    {% for flash in app.flashbag.get('message') %}
        <div class="bs-callout bs-callout-{{ flash.type }}">
            <p>{{ flash.content }}</p>
        </div>
    {% endfor %}
</div>
{% endif %}

它的主要优点是类型提示可以在 PhpStorm 中工作。

您也可以将其添加为服务提供者,

$app['flashbag'] = $app->share(function (Application $app) {
    return $app['session']->getFlashBag();
});

这使得从 PHP 中使用起来更方便(但你失去了类型提示):

$app['flashbag']->add('message',array('type'=>"danger",'content'=>"You shouldn't be here"));
于 2013-10-15T02:54:30.053 回答