我使用Whittle gem來解析模板語言,並希望匹配規則中未包含的任何內容。我非常瞭解其他模板引擎,但這更像是一次學術活動而不是生產案例。Whittle解析器條件規則激活
我遇到的問題是,分析器忽略的:id
以上:raw
的優先級,並仍在等待對{{
後:raw
標籤。
如何判斷是否不允許在表達式中應用:raw
規則,並且僅在表達式中應用:spc
規則?
解析器代碼
class Parser < Whittle::Parser
# Skip whitespaces (should not apply in :raw)
rule(:spc => /\s+/).skip!
# Various delimiters
rule("{{")^4
rule("}}")^4
rule("{%")^4
rule("%}")^4
rule("|")^4
rule("end")^4
# Defines an id (very large match)
rule(:id => /[a-zA-Z_.$<>=!:]+(\((\w+|\s+|,|")+\))?/)^2
# inline tag
rule(:inline) do |r|
r["{{", :inline_head, "}}"].as { |_,id,_| Tag::Inline.new(id) }
end
# inline tag contents
# allows "|" chaining
rule(:inline_head) do |r|
r[:inline_head, "|", :id].as { |head, _, id| head << id }
r[:id].as { |id| [id] }
r[].as { [] }
end
# block tag
rule(:block) do |r|
r["{%", :block_head, "%}", :all, "{%", "end", "%}"].as { |_,head,_,tags,_,_,_|
Tag::Block.new(head, tags)
}
end
# block tag heading
# separates all the keywords
rule(:block_head) do |r|
r[:block_head, :id].as { |head, id| head << id }
#r[:id].as { |id| [id] }
r[].as { [] }
end
# one rule to match them all
rule(:all) do |r|
r[:all,:inline].as { |all, inline| all << inline }
r[:all, :block].as { |all, block| all << block }
r[:all, :raw].as { |all, raw| all << raw }
r[].as { [] }
end
# the everything but tags rule
rule(:raw => /[^\{\}%]+/).as { |text| Tag::Raw.new(text) }^1
# starting rule
start(:all)
end
和輸入文本將是與輸出是由對象表示的抽象語法樹(它們被簡單地散列狀物體現在)。
<html>
<head>
<title>{{ title|capitalize }}</title>
</head>
<body>
<div class="news">
{% for news in articles %}
{{ news.title }}
{{ news.body | limit(100) }}
{{ tags | join(",", name) }}
{% end %}
</div>
</body>
</html>
哇作者自己!我正在儘快嘗試。謝謝 –
經過一些調整,解決了我所有的問題。偉大的項目! –