个性化阅读
专注于IT技术分析

如何在Symfony 3中使用Flash消息(在控制器和Twig视图内)

点击下载

本文概述

一个没有注意到用户所做的事情的系统, 简直糟透了。这就是为什么你总是应该在项目上实现某种通知系统的主要原因, 无论它是采用JavaScript还是以你喜欢的服务器语言在文档中添加一些额外的标记。在Symfony中, 你可以使用有用的Flash系统, 该系统允许你在访问者会话中使用自定义类别设置自定义消息。

在你的Symfony控制器中, 它们非常有用, 用于存储应在用户访问视图后显示的特殊消息。之所以称为Flash消息, 是因为它存储在会话中(它不在乎是否登录), 并且一旦用户访问(或重定向到)项目的另一条路线, 你就可以对其进行处理(显示在视图), 然后它将消失。简而言之, 一旦你检索它们, 它们就会自动从会话中消失。此功能使”刷新”消息特别适合存储用户通知。在本文中, 我们将向你展示如何在Symfony 3应用程序中使用和轻松显示Flash消息。

1.如何创建即时消息

要将Flash消息从控制器添加到会话中, 你将需要使用$ this-> addFlash方法。如果该方法扩展了symfony的Controller类, 则该方法已在你的类中可用。 flash方法的工作方式如下:

注意

请记住, 如果禁用了会话, 则不能使用addFlash方法。

/**
 * Adds a flash message to the current session for type.
 *
 * @param string $type    The type
 * @param string $message The message
 *
 * @throws \LogicException
 */
protected function addFlash($type, $message)

在旧版本的Symfony <2.7中, 有必要访问容器, 然后检索会话, 从会话中检索flashBag, 最后使用add方法(它期望与addFlash相同的参数, 因为$ this-> addFlash只是一个在Symfony <2.7中需要执行的过程的快捷方式):

// Retrieve flashbag from the controller
$flashbag = $this->get('session')->getFlashBag();

// Add flash message
$flashbag->add($type, $message);

尽管你可以使用控制器中的addFlash方法, 但也可以在最近的项目中使用Symfony 2.7方法。

以下示例显示了如何在控制器内以不同类型添加多个即显消息:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction()
    {
        // 1. Using the shortcut method of the controller

        // Adding a success type message
        $this->addFlash("success", "This is a success message");

        // Adding a warning type message
        $this->addFlash("warning", "This is a warning message");

        // Adding an error type message
        $this->addFlash("error", "This is an error message");

        // Adding a custom type message, remember the type is totally up to you !
        $this->addFlash("bat-alarm", "Gotham needs Batman");

        // 2. Retrieve manually the flashbag

        // Retrieve flashbag from the controller
        $flashbag = $this->get('session')->getFlashBag();

        // Set a flash message
        $flashbag->add("other", "This is another flash message with other type");

        // Render some twig view
        return $this->render("default/index.html.twig");
    }
}

请注意, 给定的type参数是私有数组的键, 这意味着你可以将多个闪存消息添加到单个类别, 例如, 多个成功消息和错误消息:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction()
    {
        // 1. Using the shortcut method of the controller

        // Adding 2 success type messages
        $this->addFlash("success", "This is the first success message");
        $this->addFlash("success", "This is the second success message");

        // Adding 2 error type messages
        $this->addFlash("error", "This is the first error message");
        $this->addFlash("error", "This is the second error message");

        // Render some twig view
        return $this->render("default/index.html.twig");
    }
}

如果要立即学习如何显示它们, 请跳至步骤3。

2.如何删除即时消息

如果你已经在该会话中添加了即时消息, 但由于某种原因不想再显示它, 则需要将其删除。如前所述, Flash消息一旦检索就消失了, 因此, 要删除它们, 你只需要使用Flash消息类型作为第一个参数的无指针访问get方法(不要将其值存储到变量中) :

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction()
    {
        // Retrieve flashbag from the controller
        $flashbag = $this->get('session')->getFlashBag();

        // Set a flash message
        $flashbag->add("bat-alarm", "Gotham needs Batman");

        // Retrieves the value (that isn't being assigned to a variable)
        // and therefore is "deleted" from the flashbag
        $flashbag->get("bat-alarm");

        // Render some twig view
        return $this->render("default/index.html.twig");
    }
}

现在在视图中, 蝙蝠警报类型将不再在视图中呈现, 因为先前已检索(删除)了它。

3.显示即时消息

根据添加消息的方式, 有两种显示即时消息的方法:

Symfony版本3.3中的新增功能

在Symfony 3.3中引入了app.flashes()Twig函数。

按类型显示

在Symfony> 3.3中, 你可以在应用程序的Flashes功能中提供要在视图中显示的Flash类型作为第一个参数:

{% for message in app.flashes('success') %}
    <div class="flash-notice">
        {{ message }}
    </div>
{% endfor %}

在Symfony 3.X <3.3中, 可以通过将其作为会话中flashBag对象的get函数的第一个参数提供, 在视图中显示预定义类型的所有消息:

{% for flash_message in app.session.flashBag.get('success') %}
    <div class="alert alert-success">
        {{ flash_message }}
    </div>
{% endfor %}

你只需要更改类型即可。

显示所有即时消息

太懒了以至于无法过滤视图中的消息类型?然后通过将div的类别设置为将在视图上显示的Flash消息的类别来使任务自动化, 然后在Twig中遍历所有flashbag消息。此示例与Bootstrap配合使用非常好, 因为它具有alert alert- <type>类, 该类在页面上显示具有自定义颜色的Alert div:

{% for label, messages in app.flashes %}
    {% for message in messages %}
        <div class="alert alert-{{ label }}">
            {{ message }}
        </div>
    {% endfor %}
{% endfor %}

如果你使用的是Symfony 3.X <3.3, 则还可以遍历app.session.flashbag.all对象:

{% for label, flashes in app.session.flashbag.all %}
    {% for flash in flashes %}
        <div class="alert alert-{{ label }}">
            {{ flash }}
        </div>
    {% endfor %}
{% endfor %}

编码愉快!

赞(0)
未经允许不得转载:srcmini » 如何在Symfony 3中使用Flash消息(在控制器和Twig视图内)

评论 抢沙发

评论前必须登录!