Php 从独立细枝切换到Symfony细枝:模板中的相对路径
我用了一段时间没有Symfony的树枝。现在我想将我的整个应用程序切换到symfony并使用我的旧模板,而我通常在Twig中使用的相对路径存在问题: 我对独立的细枝使用类似的东西:Php 从独立细枝切换到Symfony细枝:模板中的相对路径,php,symfony,path,twig,relative-path,Php,Symfony,Path,Twig,Relative Path,我用了一段时间没有Symfony的树枝。现在我想将我的整个应用程序切换到symfony并使用我的旧模板,而我通常在Twig中使用的相对路径存在问题: 我对独立的细枝使用类似的东西: function show_template() { global $lang; # $lang is "es" or "nl" etc $templates_dir = 'templates/'.$lang; # fallback dir if template is not f
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');
我还在模板中使用相对路径。i、 e.io index.html.twig
{% include 'includes/header.html.twig' %}
hello world
{% include 'includes/footer.html.twig' %}
这很简单,但在Symfony2中使用它在这种形式下是不可能的,正如我所看到的
正如我所看到的,我必须使用这样的东西:
$this->render('AcmeHelloBundle:Default:index.html.twig', $params);
必须更改模板以使用以下内容:
{% include '@AcmeHello/Default/includes/header.html.twig' %}
hello world
{% include '@AcmeHello/Default/includes/footer.html.twig' %}
我不介意修改我的代码/模板,添加一些新的模板逻辑模板,但我需要有灵活的路径。问题:
我通过重写控制器中的render()函数解决了这个问题
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');
}
然后,我为每种语言创建了一个Resources/views子目录,因此现在相对模板路径和回退模板也可以工作:
{% include 'includes/header.html.twig' %}
hello world
{% include 'includes/footer.html.twig' %}
如果includes/footer.html.twig在Resources/views/es/includes/中不可用,将从Resources/views/en/includes获取/