Php 如何获取细枝模板的路径
我正在使用在这个问题中找到的两个细枝模板路径 我有这样的代码:Php 如何获取细枝模板的路径,php,twig,Php,Twig,我正在使用在这个问题中找到的两个细枝模板路径 我有这样的代码: function render($request, $page, $data = array()) { global $twig, $config; $template = isset($config->template) ? $config->template : 'default'; $base = baseURI($request); return $twig->render(
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”
)。通过搜索源代码,我在一个测试文件中找到了解决方案:
$loader->getSourceContext($page)->getPath();
因此,如果要获得路径,则需要删除模板名称:
$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);
}
function template_path($page) {
global $loader;
$path = preg_replace("%" . __DIR__ . "%", "", $loader->getSourceContext($page)->getPath());
return preg_replace('%/'.$page.'$%', '', $path);
}