最理想的情况是,我希望模板看起来像这样:
interfaces {
<%= name %> {
description "<%= description %>";
mtu <%= mtu %>;
}
}但是,如果代码的计算结果为非真值,我希望不打印行。它可以被黑到ERB,在此之后,它设置print_line = true,在使用b%>评估代码为false之后,它设置print_line = false,并且只有在print_line时才打印。
但似乎改变ERB并不是那么简单,它读取整个模板,非代码部分作为print "data“插入,结果是在#result期间作为整体计算的ruby代码的单个大字符串。我要么需要在字符串扫描期间对结果代码求值,如果返回true则插入print“b%>”,要么什么都不做,否则我需要在#result中重新扫描代码,以便首先运行b%>。
使用模板似乎有点徒劳无功,如果你最终在代码块中编写了所有模板,比如:
interfaces {
<%= name %> {
<% if description %>
description "<%= description %>";
<% end%>
<% if mtu %>
mtu <%= mtu%>;
<% end%>
}
}或者:
interfaces {
<%= name %> {
<%= "description \"#{description}\";" if description %>
<%= "mtu #{mtu};" if mtu %>
}
}我需要支持各种不同的配置格式,在一些其他的配置格式中,它可能是'maximum-transfer-unit <%= mtu> bytes‘。我希望在模板中保留所有特定于平台的智能,并在模板中保留实际代码。在模板之外添加与平台无关的复杂性是没有问题的。
似乎是相对常见的用例。在我使用自己的模板语言NIHing或hacking ERB之前,有没有其他的模板语言更适合我的用例。或者遗漏了其他东西?
我已经为<%b stuff %>实现了hack,其中如果计算结果为false,则会省略整行。ERB根本不是为这样的东西而设计的,所以它非常脏,对我来说,编写自己的模板语言可能更好,除非有人能建议现有的解决方案,我可以干净利落地实现像这样的东西。
对于感兴趣的人,hack在这里http://p.ip.fi/-NeJ
最终重新发明了轮子:https://github.com/ytti/malline
发布于 2014-02-13 21:29:34
帮助器方法
def description_helper(description)
"description \"#{description}\";" if description
end
def mtu_helper(mtu)
"mtu #{mtu};" if mtu
end
interfaces {
<%= name %> {
<%= description_helper %>
<%= mtu_helper %>
}
}Decorator pattern
class MyObject
def description
'some description'
end
def mtu
nil
end
module ViewDecorator
def description
"description \"#{super}\";" if super
end
def mtu
"mtu #{super};" if super
end
end
end
o = MyObject.new
p o.description #=> "some description"
p o.mtu #=> nil
o.extend MyObject::ViewDecorator
p o.description #=> "description \"some description\";"
p o.mtu #=> nilhttps://stackoverflow.com/questions/21754735
复制相似问题