在Ruby字符串中存储ERB表达式



我正在建立一个html网页。erb文件。它包括20张具有相同元素的卡片,每张卡片都包含一个链接。我想构建一次卡片,迭代Ruby哈希来构建其余部分。

然而,一些卡片段落包含ERB表达式,我还没能找到一种方法将其包含在散列中。是否存在将此信息存储在散列中的解决方案?

下面是我如何存储信息的一个例子,用"段落"值是问题:

{
"product1" => {
"title" => "The Best Product for Your Needs",
"paragraph" => "Find out more <%= link_to 'here', 'https://www.product.com' %> about what this product can do for you."
}
}  

我尝试过regex转义,不同的引号组合('vs")和Ruby字符串插值(#{<%= ... %>})。

谢谢!

那么你要做的就是渲染"段落"文本作为ERB代码。

虽然你可以这样做,如…

<%= raw ERB.new(@hash[:product1][:paragraph]).render(binding) %>

这是一件奇怪的事情,我不建议将视图逻辑混合到传入视图的数据中。

更常见的方法是传递视图需要呈现的信息,仅此而已。例如,传入你想要链接的URL,并像这样呈现它:

# in a controller...
@product_hashes = {
"product1" => {
"title" => "The Best Product for Your Needs",
"url" => "https://www.product.com"
}
}  
# in the view
<% product_hashes.each do |product_key, product_hash| %>
<div class='title'><%= product_hash['title'] ></div>
<div class='description'> Find out more <%= link_to 'here', product['url'] %> about what this product can do for you.</div>
<% end %>

我也想知道为什么我们要传递一个哈希值。更常见的是直接在视图中使用数据库中的对象。类似…

<% @products.each do |product| %>
<div class='title'><%= product.title ></div>
<div class='description'> Find out more <%= link_to 'here', product.url %> about what this product can do for you.</div>
<% end %>

最新更新