dongliu5475 2017-07-12 07:30
浏览 42
已采纳

如何获取树枝模板的路径

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").

  • 写回答

1条回答 默认 最新

  • douershuang7356 2017-07-12 07:30
    关注

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题