Dynamically Styling an FOS UserBundle Login Page

2019-02-28 08:31发布

I am relatively new to Symfony 2 but I have a site with many different sub domains and user areas that I would like my login page styled differently, but currently it is not. I am using Symfony 2 and the FOS UserBundle and everything is currently working properly with 1 firewall in security.yml. I a overriding the FOS UserBundle Layout per the documentation, but I would like to be able to style that page differently depending on where the request is coming from, for example: microsite1.mainsite.com/user gets Style A microsite1.mainsite.com/admin gets Style B microsite2.mainsite.come/user gets Style C

I have considered a few options and I'm looking for other opinions. The first option I had considered was overriding/extending the controllers in the FOS UserBundle so that the referrer could be identified and a different twig template rendered. Another option was to use a different firewall for the different routes, but we really want to be able to have users in different microsites authenticated across all sites so one firewall is preferred. Are there any other solutions to this, or is there one way more preferable than another to tackle this relatively minor issue?

1条回答
男人必须洒脱
2楼-- · 2019-02-28 09:12

You can override the renderLogin method of the SecurityController. Here is how you could do it:

namespace Acme\UserBundle\Controller;

use FOS\UserBundle\Controller\SecurityController as BaseController;
use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\Security\Core\SecurityContext;

use Symfony\Component\HttpFoundation\Request;


class SecurityController extends BaseController
{
    /**
    * Overriding the FOS default method so that we can choose a template
    */
    protected function renderLogin(array $data)
    {
        $template = $this->getTemplate();

        return $this->container->get('templating')->renderResponse($template, $data);
    }


    /**
    * You get the subdomain and return the correct template
    */
    public function getTemplate(){

        $subdomain = $this->container->get('request')->getHost();

        if ($subdomain === "microsite1.mainsite.com"){
            $template = sprintf('AcmeUserBundle:Security:loginMicrosite1.html.%s', $this->container->getParameter('fos_user.template.engine'));
        }
        elseif($subdomain === "microsite2.mainsite.com"){
            $template = sprintf('AcmeUserBundle:Security:loginMicrosite2.html.%s', $this->container->getParameter('fos_user.template.engine'));
       }
       //blablabla
       //Customize with what you need here.

       return $template;
    }
查看更多
登录 后发表回答