Получить все переменные, используемые в файле шаблона ветки

Можно ли получить все переменные, используемые в шаблоне ветки, например: на шаблоне

<!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>

Теперь мне нужно получить все переменные, используемые в приведенном выше как массив, как

Array(1=>'navigation',2=>'a_variable')

Лучше всего, если это решит сама веточка

1 ответ

Эй, черт возьми, я слышал, что тебе нравится Твиг, поэтому я написал регулярное выражение, чтобы ты мог разобрать, пока ты разбираешь:

регулярное выражение

\{\{(?!%)\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.

PHP

$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

Regex онлайн демо PHP онлайн демо

Примечание: это просто POC, и он никогда не предназначен для использования на производстве.

Другие вопросы по тегам