[英]Silex: Redirect with Flash Data
我需要使用Silex中的消息将页面重定向到另一页面。 希望有一种Laravelesque的方法,但是我对此表示高度怀疑:
$app->redirect('/here', 301)->with('message', 'text');
然后,我想在模板中显示消息:
{{ message }}
如果没有,还有其他方法吗?
我看到Symfony中有一个getFlashBag
方法-这是我应该使用的吗? 具体来说,我正在使用Bolt Content Management系统。
是的,FlashBag是正确的方法。 在控制器中设置即显消息(您可以添加多条消息):
$app['session']->getFlashBag()->add('message', 'text');
$app->redirect('/here', 301)
并将其打印在模板中:
{% for message in app.session.getFlashBag.get('message') %}
{{ message }}
{% endfor %}
我创建了一个可能FlashBagTrait
简单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"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.