用于标题的Symfony额外控制器

时间:2016-11-23 22:26:14

标签: php symfony

例如,在Symfony2中是否可以只为标题设置一个单独的控制器?

$this->render('MYBundle::page.html.twig', array('header' => $header));

否则我需要为每个页面的每个控制器添加标头值。

1 个答案:

答案 0 :(得分:0)

我建议您使用内核响应事件全局编辑响应,例如,将侦听器定义为:

namespace Acme\DemoBundle\EventListener;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class ResponseListener
{
    public function onKernelResponse(FilterResponseEvent $event)
    {
        $request = $event->getRequest();

        // only do something when the requested format is "json"
        if ($request->getRequestFormat() != 'json') {
            return;
        }

        // only do something when the client accepts "text/html" as response format
        if (false === strpos($request->headers->get('Accept'), 'text/html')) {
            return;
        }

        // set the "Content-Type" header of the response
        $event->getResponse()->headers->set('Content-Type', 'text/plain');
    }
}

注册如下:

/src/Acme/DemoBundle/Resources/services.xml

<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    <services>
        <service id="acme.filter_response_listener" class="Acme\DemoBundle\EventListener\ResponseListener">
            <tag name="kernel.event_listener" event="kernel.response" method="onKernelResponse" />
        </service>        
    </services>
</container>

本文中的更多信息:

希望这个帮助