繁体   English   中英

从独立的Twig切换到Symfony Twig:模板中的相对路径

[英]Switching from standalone Twig to Symfony Twig: Relative paths in templates

我使用了没有Symfony的Twig已有一段时间了。 现在,我想将整个应用程序切换到symfony并使用旧模板,而我通常在Twig中使用的相对路径存在问题:

我将这样的东西与独立的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');

而且我还在模板中使用相对路径。 即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' %}

我不介意修改我的代码/模板,添加一些新的模板逻辑模板,但是我需要有灵活的路径。 问题:

  1. 如何在PHP代码中使用模板的相对路径,以能够根据语言/其他情况使用更改的templates_dir
  2. 如何在模板中使用相对路径?
  3. 如何获得备用模板/备用目录?

我通过重写控制器中的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子目录,因此现在相对模板路径和fallback模板也可以工作:

{% include 'includes/header.html.twig' %}
hello world
{% include 'includes/footer.html.twig' %}

如果无法在Resources / views / es / includes /中使用include / footer.html.twig,它将从Resources / views / zh- / includes /中获取

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM