解析Twig模板时无法识别raw过滤器的技术求助
问题:Twig解析时无法识别
raw过滤器,同其他过滤器正常 我在PHP中解析Twig模板,遍历Twig节点对象时,发现模板里的raw过滤器没有出现在节点中,但同一行的lower等过滤器能被正常识别。
我的Twig解析代码
use Twig\Environment; use Twig\Loader\FilesystemLoader; $source = new \Twig\Source(file_get_contents($val->getPath() . '/' . $val->getFilename()), $val->getFilename(), $val->getPath()); $tree = $twig->parse($twig->tokenize($source)); $vv = $tree->getNodeTag(); $functions = []; listFunctionCalls($tree, $functions); function listFunctionCalls($node, array &$list) { if ($node instanceof \Twig\Node\Node) { } if ($node instanceof \Twig\Node\Expression\FilterExpression) { $filter = $node->getNode('filter'); $value = $filter->getAttribute('value'); if ($value == 'raw') { $a = 2; } } if ($node) { foreach ($node as $child) { listFunctionCalls($child, $list); } } }
Twig模板代码
{# /** * @file * Theme override to display a two-column layout. * * Available variables: * - content: The content for this layout. * - attributes: HTML attributes for the layout <div>. */ #} {% if content %} <div{{ attributes|raw|lower }}> {% if content.first %} <div {{ region_attributes.first.addClass('layout__region', 'layout__region-- first') }}> {{ content.first }} </div> {% endif %} {% if content.second %} <div {{ region_attributes.second.addClass('layout__region', 'layout__region--second') }}> {{ content.second }} </div> {% endif %} </div> {% endif %}
原因分析
Twig的raw过滤器并非普通的FilterExpression节点,它的作用是取消自动转义,在编译阶段会被转换为节点的isRaw标记,而非保留为常规过滤器节点。因此直接遍历FilterExpression找不到raw。
解决方案
修改遍历函数,通过检查节点的isRaw()方法来识别raw过滤器的使用:
function listFunctionCalls($node, array &$list) { // 检测是否是标记为raw的表达式 if (method_exists($node, 'isRaw') && $node->isRaw()) { // 此处捕获到使用了raw的节点 $a = 2; } // 处理其他常规过滤器 if ($node instanceof \Twig\Node\Expression\FilterExpression) { $filter = $node->getNode('filter'); $value = $filter->getAttribute('value'); // 示例:处理lower过滤器 if ($value == 'lower') { // 逻辑代码 } } // 递归遍历子节点 if ($node instanceof \Twig\Node\Node) { foreach ($node as $child) { listFunctionCalls($child, $list); } } }
- 所有被
raw修饰的表达式节点都会带有isRaw()方法,调用该方法可判断是否启用了取消转义。 - 原代码仅检测常规过滤器节点,忽略了Twig对
raw的特殊处理逻辑,因此无法捕获到raw的使用。
内容的提问来源于stack exchange,提问作者Thomas Musa
相关产品推荐
相关产品推荐

