我是Ruby的新手,我尝试渲染一个名为database.rb的单独文件中的数组:
Data = [
{
title: "First",
content: "Lorem ipsum...",
photo: "image1"
},
{
title: "Second",
content: "Eventually ...",
photo: "image2"
},
{
title: "Third",
content: "also to Kim’s ....",
photo: "image3"
}
]
我现在想在视图中渲染此数组。
在我的app.rb中,我有这段代码:
require "sinatra"
require "sinatra/activerecord"
require_relative "database"
["/", "/articles"].each do |path|
get path do
@database = Data
erb :index
end
end
在我看来索引:
<% @database.each do |article| %>
<!-- Blog Post -->
<div class="card mb-4">
<img class="card-img-top" src="<%= article.photo %>" alt="">
<div class="card-body">
<h2 class="card-title oink"><%= article.title %></h2>
<p class="card-text oink"><%= article.content %></p>
</div>
<div class="card-footer text-muted">
</div>
</div>
<% end %>
如何让它发挥作用?因为似乎无法识别属性标题,内容和照片。 我该做什么?创建模型?但怎么样?
答案 0 :(得分:3)
您的数组由哈希项组成。如果你想坚持使用哈希,这是访问值的方法(按键)
<!-- Blog Post -->
<div class="card mb-4">
<img class="card-img-top" src="<%= article[:photo] %>" alt="">
<div class="card-body">
<h2 class="card-title oink"><%= article[:title] %></h2>
<p class="card-text oink"><%= article[:content] %></p>
</div>
<div class="card-footer text-muted">
</div>
</div>
否则,如果您想拥有方法,可以使用Ruby Struct
Article = Struct.new(:title, :content, :photo)
Data = [
Article.new("First", "Lorem ipsum...", "image1"),
Article.new("Second", "Eventually ...", "image2"),
Article.new("Third", "also to Kim’s ....", "image3")
]
现在你可以像在你的代码段中那样做了