如何获取树枝模板的路径

I'm using two twig template paths found in this question 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);

and I have code like this:

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));
}

and what I need is to get path of the template so I can use it as 'path' variable (so I can use current path for assets like "{{path}}/img/foo.png").

By searching source code I found solution in one of the test file:

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

so if you want to have apth you need to remove template name:

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

and if you want to get relative path you can use:

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

You can wrap this in a function:

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