[英]render array in view with Ruby
I'm new to Ruby and I try to render an array which is in a separate file called database.rb: 我是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"
}
]
I now want to render this array in a view. 我现在想在视图中渲染此数组。
In my app.rb I have this code: 在我的app.rb中,我有以下代码:
require "sinatra"
require "sinatra/activerecord"
require_relative "database"
["/", "/articles"].each do |path|
get path do
@database = Data
erb :index
end
end
In my view index: 在我看来,索引:
<% @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 %>
How to get this to work? 如何使它工作? Because it seems that properties title, content and photo are not recognized. 因为似乎无法识别属性标题,内容和照片。 What I should do? 我该做什么? creating a model? 创建一个模型? but how? 但是如何?
Your array is made of hash items. 您的数组由哈希项组成。 If you want to stick with hashes, this is the way to access values (by key) 如果您要坚持使用哈希,这是通过键访问值的方法
<!-- 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>
Otherwise, if you want to have methods, you might use Ruby Struct
否则,如果要使用方法,则可以使用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")
]
Now you can do it like in your snippet 现在,您可以像在代码段中一样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.