【问题标题】:Iterating over an embedded document in Haml在 Haml 中迭代嵌入的文档
【发布时间】:2012-07-12 06:07:41
【问题描述】:

我在 Mongodb 文档中有一个嵌入文档。 Mongodb 文档长这样:

[_id] => home
[url] => /
[type] => homepage
[people] => Array (
    [0] => Array (
        [name] => John Smith
        [rewrite] => john-smith
    )
    [1] => Array (
        [name] => John Q. Public
        [rewrite] => john-q-public
    )
)

我正在尝试遍历 people 嵌入文档。在我的 app.rb 中,我将对象传递给 haml,如下所示:

DB = Mongo::Connection.new.db("website", :pool_size => 5, :timeout => 5)                                                              
pages = DB.collection('pages')                                                                                                      

get '/' do                                                                                                                          
  home = pages.find_one( :type => "homepage" )                                                                                                                                                                     
  haml :index, :attr_wrapper => '"', :locals => {:items => home}                            
end                                                                                                                                 

在我的 index.haml 中,我可以像这样遍历整个文档:

-items.each do |item|
  %h2= item

但是我怎样才能遍历 people 嵌入文档呢?我想做这样的事情:

-items.people.each do |person|
  %h2= person.name, person.rewrite

另外,如果我使用了不正确的术语,请纠正我;我是 Mongo、Haml、Sinatra 等的新手。

【问题讨论】:

    标签: mongodb sinatra haml


    【解决方案1】:

    也许我应该多学习一点 Ruby 语法...这是我能够迭代到我的 people 嵌入式文档的方法:

    -items["people"].each do |person|
      %h2= person["name"], person["rewrite"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      • 2012-12-10
      • 2018-08-21
      • 2020-11-06
      • 2012-05-11
      • 2011-03-10
      相关资源
      最近更新 更多