本文介绍了获取树枝模板文件中使用的所有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以获取树枝模板中使用的所有变量例如:在模板上
Is it possible to get all variables used in a twig template Eg: On template
<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<ul id="navigation">
{% for item in navigation %}
<li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>
<h1>My Webpage</h1>
{{ a_variable }}
</body>
</html>
现在我需要将上面使用的所有变量作为一个数组获取,例如
Now i need to get all variables used in the above as an array like
Array(1=>'navigation',2=>'a_variable')
最好由树枝自身解决
推荐答案
您好,我听说您喜欢Twig,所以我写了一个正则表达式,以便您在解析时可以解析:
Yo dawg, I heard you like Twig so I wrote a regex so you can parse while you parse:
\{\{(?!%)\s* # Starts with {{ not followed by % followed by 0 or more spaces
((?:(?!\.)[^\s])*) # Match anything without a point or space in it
\s*(?<!%)\}\} # Ends with 0 or more spaces not followed by % ending with }}
| # Or
\{%\s* # Starts with {% followed by 0 or more spaces
(?:\s(?!endfor)(\w+))+ # Match the last word which can not be endfor
\s*%\} # Ends with 0 or more spaces followed by %}
# Flags: i: case insensitive matching | x: Turn on free-spacing mode to ignore whitespace between regex tokens, and allow # comments.
$string = '<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<ul id="navigation">
{% for item in navigation %}
<li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>
<h1>My Webpage</h1>
{{ a_variable }}
</body>
</html>';
preg_match_all('/\{\{(?!%)\s*((?:(?!\.)[^\s])*)\s*(?<!%)\}\}|\{%\s*(?:\s(?!endfor)(\w+))+\s*%\}/i', $string, $m);
$m = array_map('array_filter', $m); // Remove empty values
array_shift($m); // Remove first index [0]
print_r($m); // Print results
这篇关于获取树枝模板文件中使用的所有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!