如何在 TWIG 函数中获取当前模板名称 [英] How to get current template name in a TWIG function

查看:31
本文介绍了如何在 TWIG 函数中获取当前模板名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我创建了一个自定义树枝函数:templateName.

let's say I have created a custom twig function: templateName.

$twig = new Twig_Environment($loader);
$twig->addFunction('templateName', new Twig_Function_Function('twig_template_name', array('needs_environment' => true)));

有没有办法在 php.ini 中获取当前模板的名称?我想像这样:

Is there a way to get the name of the current template(s) in php. I imagine something like this:

function twig_template_name(Twig_Environment $env, $values = null) {
  return $env->getCurrentTemplateName();
}

提前致谢.

推荐答案

对于需要回答初始问题的每个人,我找到了一个 twig 本身在 Twig_Error 类中使用的解决方案.

For everyone who needs an answer to the initial question, I found a solution that twig itself is using in the Twig_Error class.

protected function guessTemplateInfo()
{
    $template = null;
    foreach (debug_backtrace() as $trace) {
        if (isset($trace['object']) && $trace['object'] instanceof Twig_Template && 'Twig_Template' !== get_class($trace['object'])) {
            $template = $trace['object'];
        }
    }

    // update template filename
    if (null !== $template && null === $this->filename) {
        $this->filename = $template->getTemplateName();
    }

    /* ... */

最好的问候!

这篇关于如何在 TWIG 函数中获取当前模板名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆