如何配置symfony2 / 3来处理服务于不同视图的不同域?

时间:2016-09-04 15:46:55

标签: symfony

是否可以配置symfony2 / 3来处理具有不同视图的多个域?

例如我有site1.com和site2.com,我会在app / Resources / views中创建一个site1和site2文件夹,并根据域提供不同的模板集。

模型和控制器应该是通用的,因此site1.com/mypage和site2.com/mypage应该使用不同的布局提供相同的内容。

欢迎任何与之相关的建议或最佳实践。

谢谢

2 个答案:

答案 0 :(得分:2)

检查控制器中的主机:

namespace Acme\FooBundle\Controller;

use Symfony\Component\HttpFoundation\Request;

class DemoController
{
    public function showAction(Request $request)
    {
        switch($request->getHost())
        {
            case 'site1.com':
                return $this->render('site1/show.html.twig');
            break;
            case 'site2.com':
                return $this->render('site2/show.html.twig');
            break;
            default:
                return $this->render('default/show.html.twig');
        }        
    }
}

编辑:更通用的东西

创建onKernelRequest侦听器:

namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class DomainRequestListener
{
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();

        $host = explode('.',$request->getHost());

        $request->request->attributes->set('_domain',$host[0]);
    }
}

在services.yml中添加此侦听器:

    app.listener.domain_request:
        class: AppBundle\EventListener\DomainRequestListener
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest}

然后你可以使用' _domain'所有控制器中的路由参数:

return $this->render($request->attributes->get('_domain').'/show.html.twig');

答案 1 :(得分:1)

未经测试,但我希望以下内容可行。您将要注册使用Twig加载器服务(负责定位模板)的内核请求侦听器,并根据请求的主机名注册路径。

创建请求侦听器:

<?php

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class RegisterTwigPathSubscriber implements EventSubscriberInterface
{
    private $loader;

    public function __construct(\Twig_Loader_Filesystem $loader)
    {
        $this->loader = $loader;
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::REQUEST => 'registerTwigPath'
        ];
    }

    public function registerTwigPath(GetResponseEvent $event)
    {
        $host = $event->getRequest()->getHost();
        $path = '...'; // determine path based on hostname
        $this->loader->addPath($path, 'Theme'); // the second argument is a namespace for templates located under this folder and can be chosen
    }
}

注册事件监听器:

services:
    register_twig_path_listener:
        class: RegisterTwigPathSubscriber
        arguments: ["@twig.loader"]
        tags: [{ name: kernel.event_subscriber }]

现在引用模板:

return $this->render('@Theme/path/to/actual/template.html.twig');