我有一个哈希数组,我正在将其传递到 HAML 页面。
array = [{"name" => "a", "age" => 1}, {"name" => "b", "age" => 2}]
我想迭代并显示此信息。我尝试过这样做
#{locals[:array]}.each do |#{:value}|
%h2 #{:value["name"]}
但是这不起作用。整个哈希值刚刚被显示。如何迭代并显示这些元素?
在伪代码中,我想执行以下操作:
for each element in array:
print element["name"] // I want to display this information in different HTML tags.
print element["age"]
更新:这是我的 HAML 文件。
!!!
%html
%head
%link{:href => "css/batchscreen.css", :rel => "stylesheet", :type => "text/css"}/
%body
.container
locals[:array].each do |element|
.story
%h2 Name: #{element['name']}
最佳答案
您的问题是您使用了字符串插值 #{}
,它获取大括号中的任何内容并从中生成一个字符串(调用 to_s
我相信)。使用“each”,您需要迭代字符串。 |#{:value}|
相同。
底线:仅当您想在字符串(字符序列)中包含某些内容时,才使用 #{}
。
就您而言,您需要在 haml 模板中编写以下内容(请注意,您需要适当的缩进)
- locals[:array].each do |element|
%h2 Name: #{element['name']}, Age: #{element['age']}
此外,考虑使用符号作为哈希键,如下所示
array = [{:name => "a", :age => 1}, {:name => "b", :age => 2}]
甚至(使用较新版本的 ruby)
array = [{name: "a", age: 1}, {name: "b", age: 2}]
然后相应地调整标题中的字符串插值 (%h2
)(它变成类似 #{element[:name]}
。
关于ruby - 在 HAML 中迭代 ruby 哈希数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26053743/