Reputation: 33
I used Twig without Symfony for some time now. Now I want to switch my whole application to symfony and use my old templates and i have problems with relative paths which I usually use with Twig:
I use something like this with standalone Twig:
function show_template() {
global $lang;
# $lang is "es" or "nl" etc
$templates_dir = 'templates/'.$lang;
# fallback dir if template is not found in the main location
$fallback_dir = 'templates/en'
$loader = new Twig_Loader_Filesystem(array($templates_dir, $fallback_dir));
$twig = new Twig_Environment($loader, array(
# 'cache' => './cache',
));
# $file is relative path to $templates_dir
return $twig->render($file, $params);
}
show_template('index.html.twig');
and I also use relative paths in templates. i.e. io index.html.twig
{% include 'includes/header.html.twig' %}
hello world
{% include 'includes/footer.html.twig' %}
this is pretty simple but using this in Symfony2 is not possible in this form as I can see.
As I can see I have to use something like this:
$this->render('AcmeHelloBundle:Default:index.html.twig', $params);
And templates have to be changed to use following:
{% include '@AcmeHello/Default/includes/header.html.twig' %}
hello world
{% include '@AcmeHello/Default/includes/footer.html.twig' %}
I don't mind adapting my code/templats adding some new templating logic templates but I need to have flexible paths. Questions:
Upvotes: 0
Views: 1064
Reputation: 33
I solved it by overriding the render() function in my controller.
public function render($template, array $parameters = array(), Response $response = null) {
# default language/directory
$lang = $this->container->getParameter('lang');
$this->container->get('twig.loader')->addPath(__DIR__.'/../Resources/views/'.$lang);
## falback language/directory
if ($lang != 'en') {
$this->container->get('twig.loader')->addPath(__DIR__.'/../Resources/views/en');
}
return parent::render($template, $parameters, $response);
}
public function myAction() {
return $this->render('index.html.twig');
}
I then made a Resources/views subdirectories for every language, so now relative template paths and fallback templates work too:
{% include 'includes/header.html.twig' %}
hello world
{% include 'includes/footer.html.twig' %}
If includes/footer.html.twig is not availables in Resources/views/es/includes/ it will be taken from Resources/views/en/includes/
Upvotes: 1