2013-05-26 21 views
6

是否有可能得到一個樹枝模板 如使用的所有變量:在模板獲取在樹枝模板文件中使用的所有變量

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

它的最好的,如果它通過駕駛室小枝本身

+0

爲什麼'item'不是變量? – HamZa

+1

@HamZaDzCyber​​DeV它在模板內部使用,但它不是模板的參數。調用'render($ op_template)'的人不關心'item'。 – delnan

+0

@delnan這個問題被標記爲'regex',正則表達式無法找到/檢測這樣的事情,因此從邏輯上講,如果你想考慮這些細節,你不能編寫通用的東西。說到Twig本身,它似乎[不可能](http://stackoverflow.com/q/12799094/),所以我們可能必須用正則表達式來完成,但我們需要指定「規則」來比賽。 – HamZa

回答

20

喲耶得到解決,我聽說你喜歡的樹枝,所以我寫了一個正則表達式小號Ø當你分析,你可以解析:

正則表達式

\{\{(?!%)\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 online demoPHP online demo

注意:這僅僅是一個POC,並且從未想過要在生產中使用。

+6

我希望我能第一個詞組給予好評兩次) – zerkms

+3

+1,洛爾 –

相關問題