如何配置 symfony2/3 来处理服务于不同视图的不同域? [英] How to configure symfony2/3 to handle different domains serving different views?

查看:24
本文介绍了如何配置 symfony2/3 来处理服务于不同视图的不同域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将 symfony2/3 配置为处理 1 个以上具有不同视图的域?

Is it possible to configure symfony2/3 to handle more than 1 domain with different views?

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

For example I have site1.com and site2.com, I would create a site1 and site2 folders inside app/Resources/views and serve a different set of templates depending on the domain.

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

Models and controllers should be in common so site1.com/mypage and site2.com/mypage should serve the same content with different layout.

欢迎任何与之相关的建议或最佳做法.

Any suggestion or best practice related to it is welcome.

谢谢

推荐答案

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

Not tested, but I expect the following should work. You'll want to register a kernel request listener that uses the Twig loader service (responsible for locating the templates) and registers a path based on the request's hostname.

创建一个请求监听器:

<?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');

这篇关于如何配置 symfony2/3 来处理服务于不同视图的不同域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆