Ruby Mustache API是否有办法从模板中返回键名称?使用Mustache Ruby API提取键名称?
举个例子来说:
require 'mustache'
m = Mustache.new
m.template = "Hello {{first_name}} {{last_name}}"
我想调用API - 但我不知道它是什么 - 返回键名:
[:first_name, :last_name]
或相似的东西。
Ruby Mustache API是否有办法从模板中返回键名称?使用Mustache Ruby API提取键名称?
举个例子来说:
require 'mustache'
m = Mustache.new
m.template = "Hello {{first_name}} {{last_name}}"
我想调用API - 但我不知道它是什么 - 返回键名:
[:first_name, :last_name]
或相似的东西。
没有明确的方式来做到这一点,但作为一个开始,你可能会考虑以下几点:
>> pp Mustache::Template.new('Hello {{first_name}} {{person.last_name}}').tokens
[:multi,
[:static, "Hello "],
[:mustache, :etag, [:mustache, :fetch, ["first_name"]]],
[:static, " "],
[:mustache, :etag, [:mustache, :fetch, ["person", "last_name"]]]]
应该很容易编写提取相关按键遍历。
在这一点上,我不认为这是由API支持。我搜索了胡子版本0.99.4的源代码。我找到的最近的是context.rb中的has_key?
和fetch
方法。读完这些方法后,看起来这些密钥没有被缓存。
巧合的是,我已经做到了。
IIRC所有我需要做的是实现一个tokens
方法,像这样:
class Mustache::Template
def tokens(src = @source)
p = ::Mustache::Parser.new
p.otag = PMustache::DEFAULT_MUSTACHE_OTAG
p.ctag = PMustache::DEFAULT_MUSTACHE_CTAG
p.compile(src)
end
end
(您可以忽略PMustache::DEFAULT_MUSTACHE_xTAG
S,他们设置默认的分隔符。)
喂养它的模板像这样:
[1] pry(main)> require 'pmustache'
=> true
[2] pry(main)> f = Mustache.new
=> #<Mustache:0x007fce2192b520>
[3] pry(main)> f.template = "this is {{a}} test"
=> "this is {{a}} test"
允许访问令牌:
[5] pry(main)> f.template.tokens
=> [:multi,
[:static, "this is "],
[:mustache, :etag, [:mustache, :fetch, ["a"]]],
[:static, " test"]]
从那里,我想你基本上要在:mustache
标签:
[6] pry(main)> p_toks = lambda { |tok| (tok.instance_of? Array) && (tok[0] == :mustache) }
=> #<Proc:[email protected](pry):6 (lambda)>
[7] pry(main)> f.template.tokens.find_all(&p_toks)
=> [[:mustache, :etag, [:mustache, :fetch, ["a"]]]]
我曾在那里,以及一些其他的两轮牛车;我们有点分隔的模板变量,并将它们呈现在用户界面上(可能或多或少是你在做什么),所以我们可以按功能对它们进行分组,从JSON对象加载它们,等等等等。
您可能只想要某些标记类型;将令牌从编译模板中拉出是非常简单的,所以一旦你抛出一些模板,你就会看到你需要做什么。
没有'[4]'。 –
pmustache只是我的附加代码库。 –
感谢分享。你是否考虑过向{? –
有些人喜欢这看起来做工精细,当你只有简单的键名:
tokens = Mustache::Template.new('Hello {{first_name}} {{person.last_name}}').tokens
pp tokens.find_all{|token| token.is_a?(Array) && token[0] == :mustache }.map{|token| token[2][2]}
为了您确切的愿望,你可能需要的东西,如:
pp tokens.find_all{|token| token.is_a?(Array) && token[0] == :mustache }.map{|token| token[2][2].last.to_sym}.flatten
>> Mustache::Template.new('Hello {{first_name} {{last_name}}').tags
[
[0] "first_name",
[1] "last_name"
]
这个相关的问题有一个PHP相关的答案:http:// stackoverflow。com/questions/9355364/mustache-retrieve-list-hash-of-tags-from-a-template但它不回答我的问题。 –
我也在[Mustache GitHub问题页面](https://github.com/defunkt/mustache/issues/134)上提出这个问题。 –