Rendering Twig templates from Symfony Repository without Using Dependency Injection (DIC)

Sometimes it’s useful to access Twig templates from a Symfony repository, one could argue that this goes against a repository’s role, but if you think of Twig template files or Twig strings perhaps grabbed from a database as data, then this coincides nicely with the function of a repo.

These arguments aside, whatever your situation, if you need to render Twig from a Symfony repository, you do NOT have to pass the Twig container from a controller to a repo to access Twig — just initialize a new Twig Container object then render it’s contents as illustrated in these two repo methods below.


function getEmailHeaderNew(){

   $TwigContainer = new \Twig_Environment(new \Twig_Loader_String());
   $path = $this->container->getParameter('kernel.root_dir').'/../Resources/views/email-header.html.twig';
   $emailHeader=@$TwigContainer->render(file_get_contents($path) );

   return @$emailHeader;
}


function getEmailFooterNew($site=''){

   if(empty($site)){ $site=$this->siteCanonical;}
   $site=str_ireplace('www.','',$site);

   $TwigContainer= new \Twig_Environment(new \Twig_Loader_String());
   $path = $this->container->getParameter('kernel.root_dir').'/../Resources/views/email-footer.html.twig';
   $emailHeader=@$TwigContainer->render(file_get_contents($path),array('site'=>$site) );
   return @$emailHeader;
}

admin has written 5 articles

Leave a Reply

Your email address will not be published. Required fields are marked *