You need to enable JavaScript to run this app. Rails视图调用.html_safe后ERB标签仍被转义无法输出值如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Rails视图调用.html_safe后ERB标签仍被转义无法输出值如何解决

问题原因

你在辅助方法中拼接HTML字符串时写入的<%= %>ERB标签无法被执行,因为ERB模板的解析和执行发生在辅助方法调用之前,辅助方法返回的字符串中即使包含ERB标签,也只会被当做普通文本输出,html_safe只能避免HTML标签被转义,无法触发ERB代码的二次执行。

解决方法

1. 传参调整

局部模板调用tooltip_formula时,将当前的simulation局部变量作为参数传入:

<p class="text-xs">
  <%= tooltip_formula(["Prix d'achat", "+", "Frais de notaire"], simulation).html_safe %>
</p>

2. 辅助方法修改

调整两个辅助方法,直接用Ruby代码计算取值,不要在字符串中写入ERB标签:

module SimulationsHelper
  # 新增simulation参数
  def tooltip_formula(formula_elements_array, simulation)
    formula_elements_array.map.with_index do |formula_element, i|
      i.even? ? tooltip(formula_element, simulation) : formula_element
    end.join(' ')
  end

  # 新增simulation参数,直接取值插值
  def tooltip(formula_element, simulation)
    tooltip = 'class1'
    tooltiptext = 'class2'
    # 直接调用对应方法拿到数值,不需要写ERB标签
    sim_value = simulation.send(convert_formula_element_to_corresponding_simulation_variable(formula_element))
    "<span class='#{tooltip}'>
      #{formula_element}
      <span class='#{tooltiptext}'>
        #{sim_value}
      </span>
    </span>"
  end
end

安全提示

如果担心send方法存在安全风险,可以给convert_formula_element_to_corresponding_simulation_variable返回的方法名加白名单校验,只允许调用约定好的属性方法,避免恶意调用。


内容的提问来源于stack exchange,提问作者Mathieu EUSTACHY

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 19:36:07