2017-07-12 47 views
1

我用了这个问题How do I specify two locations for Twig templates?如何获得

$template = isset($config->template) ? $config->template : 'default'; 
$templates_dir = $root . 'templates' . DIRECTORY_SEPARATOR; 
if (isset($config->template) && $config->template != 'default') { 
    $template = array($templates_dir . $config->template, $templates_dir . 'default'); 
} else { 
    $template = $templates_dir . 'default'; 
} 

$loader = new Twig_Loader_Filesystem($template); 

发现了两个枝杈模板路径树枝模板的路径,我有这样的代码:

function render($request, $page, $data = array()) { 
    global $twig, $config; 
    $template = isset($config->template) ? $config->template : 'default'; 
    $base = baseURI($request); 
    return $twig->render($page, array_merge(array(
     "path" => $base . '/templates/' . $template, 
     "root" => $base 
    ), $data)); 
} 

什么,我需要的是获取模板的路径,以便我可以将其用作'path'变量(这样我可以使用"{{path}}/img/foo.png"之类资产的当前路径)。

回答

1

通过搜索源代码,我发现解决方案在测试文件之一:

$loader->getSourceContext($page)->getPath(); 

,所以如果你想有apth您需要删除模板名称:

$page = 'admin.html'; 
$path = $loader->getSourceContext($page)->getPath(); 
$path = preg_replace('%/'.$page.'$%', '', $path); 

,如果你想得到相对路径你可以使用:

preg_replace("%" . __DIR__ . "%", "", $path); 

你可以把它包装在一个函数中:

function template_path($page) { 
    global $loader; 
    $path = preg_replace("%" . __DIR__ . "%", "", $loader->getSourceContext($page)->getPath()); 
    return preg_replace('%/'.$page.'$%', '', $path); 
}