我使用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>
哇作者自己!我正在尽快尝试。谢谢 –
经过一些调整,解决了我所有的问题。伟大的项目! –