【问题标题】:Storing ERB Expression in a Ruby String将 ERB 表达式存储在 Ruby 字符串中
【发布时间】:2021-08-26 15:52:47
【问题描述】:

我正在 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."
  }
}  

我尝试了正则表达式转义 \、不同的引号组合('")和 Ruby 字符串插值(#{&lt;%= ... %&gt;})。

谢谢!

【问题讨论】:

  • 我一定错过了什么。我不明白问题是什么。你可以说得更详细点吗?在我看来,它应该完全按照你写的那样工作。
  • 如果您想评估段落内的 ERB expr,您可能需要 render before you print inside your component,然后使用 &lt;%= raw ERB.new(item["paragraph"]).result(binding) %&gt; 打印到您的组件中
  • @MichaelB,它在字符串和 404 页面内的 ERB 上引发错误。

标签: ruby-on-rails ruby erb


【解决方案1】:

所以您要做的就是将“段落”文本呈现为 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 %>

【讨论】:

  • 感谢您的回答!对象不存储在数据库中,这就是我选择前一个选项的原因。问题是我需要将网址存储在一个句子中,并且每张卡片上的句子和链接都会有所不同。我尝试了您的建议,但无法让它们与句子中嵌入的 url 一起使用。
  • 你能发布错误信息吗?但是,是的,一般来说,我可能会建议采取不同的方法。甚至只是使用原始 HTML 而不是使用 ERB 插值,或者为每个产品创建一个模板文件并传入一个视图部分数组来进行渲染。
  • 实际上 - 另一种选择是使用 markdown 语法编写文本字段并使用 gem 解析为 html(将链接变为链接)。 github.com/gettalong/kramdownKramdown::Document.new(text).to_html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-13
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2012-01-28
相关资源
最近更新 更多