使用Mustache Ruby API提取密钥名称?

时间:2012-06-06 19:26:05

标签: ruby mustache

Ruby Moustache API是否有办法从模板中返回键名?

举个例子:

require 'mustache'
m = Mustache.new
m.template = "Hello {{first_name}} {{last_name}}"

我想进行API调用 - 但我不知道它是什么 - 返回键名:

[:first_name, :last_name]

或类似的东西。

5 个答案:

答案 0 :(得分:2)

巧合的是,我已经做到了。

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,他们设置默认分隔符。)

像这样给它一个模板:

[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:0x007fce228b0b08@(pry):6 (lambda)>
[7] pry(main)> f.template.tokens.find_all(&p_toks)      
=> [[:mustache, :etag, [:mustache, :fetch, ["a"]]]]

我也有其他的hackery;我们有点分隔模板变量并在用户界面上显示它们(可能或多或少你正在做的事情)所以我们可以按功能对它们进行分组,从JSON对象加载它们,等等等等。

您可能只需要某些令牌类型;将令牌从编译模板中拉出来是很简单的,所以一旦你在它上面放了一些模板,你就会看到你需要做什么。

答案 1 :(得分:1)

没有专门的方法可以做到这一点,但作为一个开始你可能会考虑以下几点:

>> 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"]]]]

编写提取相关键的遍历应该相当容易。

答案 2 :(得分:0)

此时,我认为这不受API的支持。我搜索了胡子版本0.99.4的源代码。我找到的最接近的是context.rb中的has_key?fetch方法。阅读这些方法后,似乎没有缓存密钥。

答案 3 :(得分:0)

当你只有简单的键名时,有些像这样看起来很好用:

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

答案 4 :(得分:0)

使用Mustache::Template#tags

>> Mustache::Template.new('Hello {{first_name} {{last_name}}').tags
[
    [0] "first_name",
    [1] "last_name"
]
相关问题