如何获取树枝模板的路径

时间:2017-07-12 07:30:43

标签: php twig

我正在使用此问题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 个答案:

答案 0 :(得分: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);
}