You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ruby哈希中存储包含ERB表达式的字符串用于html.erb模板渲染

解决方案

方案1:使用Proc封装动态内容(最推荐)

你不需要将ERB标签硬写入字符串,直接把段落的动态逻辑封装为Proc存储到哈希中,渲染时直接调用即可:
哈希定义示例:

# 可定义在控制器或者erb文件头部
@product_cards = {
  "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." }
  }
}

卡片渲染示例:

<% @product_cards.each do |product_key, card_info| %>
<div class="card">
  <h3><%= card_info["title"] %></h3>
  <p><%= card_info["paragraph"].call.html_safe %></p>
</div>
<% end %>

调用Proc后加html_safe是为了避免生成的链接标签被自动转义为纯文本。

方案2:拆分动静态内容

如果不想使用Proc,也可以将段落中的静态文本和动态链接参数分开存储,渲染时再拼接:
哈希定义示例:

@product_cards = {
  "product1" => {
    "title" => "The Best Product for Your Needs",
    "para_prefix" => "Find out more ",
    "link_text" => "here",
    "link_url" => "https://www.product.com",
    "para_suffix" => " about what this product can do for you."
  }
}

卡片渲染示例:

<% @product_cards.each do |product_key, card_info| %>
<div class="card">
  <h3><%= card_info["title"] %></h3>
  <p>
    <%= card_info["para_prefix"] %>
    <%= link_to card_info["link_text"], card_info["link_url"] %>
    <%= card_info["para_suffix"] %>
  </p>
</div>
<% end %>

方案3:手动触发ERB渲染(不推荐)

如果你确实需要存储带ERB标签的原始字符串,可以手动调用ERB渲染能力处理字符串:
哈希定义示例:

@product_cards = {
  "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."
  }
}

卡片渲染示例:

<% @product_cards.each do |product_key, card_info| %>
<div class="card">
  <h3><%= card_info["title"] %></h3>
  <p><%= ERB.new(card_info["paragraph"]).result(binding).html_safe %></p>
</div>
<% end %>

该方案存在XSS安全风险且性能较低,仅作参考不建议在生产环境使用。

内容的提问来源于stack exchange,提问作者Genevieve McAllister

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 09:42:03