【问题标题】:Parse/search for a certain function in twig templates解析/搜索树枝模板中的某个功能
【发布时间】:2014-02-18 01:58:18
【问题描述】:

在最新版本的twig 中,客户功能将被实现为Twig_SimpleFunctions,因为旧方法已被弃用。

我有一个自定义翻译功能,用于使用资源包处理消息格式化程序:

{{ trans('key') }}

我正在构建一个 PHP 脚本来遍历我的所有模板以检索这些密钥。我不希望在此脚本中呈现模板,因为我没有要传递给模板的所有变量。使用 load() 加载模板时不会调用函数(这对性能很重要),因此我需要一个词法分析器来解析我的模板。

不幸的是,没有太多关于这方面的信息,所以很难说从哪里开始。

如何添加客户词法分析器来解析 {{ trans('key') }} 之类的函数?

或者,如果有更好/更简单的方法来实现这一点,我当然很想知道!

【问题讨论】:

    标签: php twig


    【解决方案1】:

    解决方案真的很简单。我们需要获取所有模板,加载每个模板,然后在其上运行解析器以生成 AST。然后我们就通过 AST 来挑选我们想要的东西。无需编译模板。

    这是如何做到的:

    public function process($node) 
    {
        // Process nodes that are function expressions
        if ($node instanceof \Twig_Node_Expression_Function) {
            // Check the function name
            if ($node->getAttribute('name') == 'trans') {
                // Grab the argument
                foreach ($node->getNode('arguments') as $argument) { 
                    $key = eval('return ' . $this->twig->compile($argument) . ';' );
    
                    if (!in_array($key, $translationKeys)) {
                        $this->trans[] = $key;
                    }
    
                    // I only needed the first argument in my implementation
                    break; 
                }
            }
        }
    
        // Recursively loop through the AST
        foreach ($node as $child) {
            if ($child instanceof \Twig_Node) {
                process($child);
            }
        }
    }
    

    提示:如果您是从外部文件而不是字符串加载模板,那么您需要使用getContent() 来获取文本形式的模板:

    $parsed = $twig->parse($twig->tokenize($loader->getSource($template)));
    

    【讨论】:

      猜你喜欢
      • 2018-07-23
      • 1970-01-01
      • 2012-07-27
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      相关资源
      最近更新 更多