在rjerb模板中输出HTML

Output HTML in a RJ ERB template

本文关键字:输出 HTML rjerb      更新时间:2023-09-26

这可能有点傻,但我不能让它工作…

我有vacation.js.erb,它生成一些javascript来在ajax调用完成时更新页面。该文件的源文件如下所示:

$('semantic').replace('<div id="semantic"></div>');
<%
    html = '<table class="ajax">'
    html += "<tr><td>EU - 27</td><td>#{@eu.value.value} days</td></tr>"
    html += "<tr><td>#{@source.location.value}</td><td>#{@source.value.value } days></td></tr>" unless @source.location.value.blank?
    html += "<tr><td>#{@cv.country.name}</td><td>No Data Available</td></tr>" if @source.location.value.blank?
    html += "<tr><td>#{@target.location.value}</td><td>#{@target.value.value } days></td></tr>" unless @target.location.value.blank?
    html += "<tr><td>#{@vacancy.country.name}</td><td>#{@target.value.value } days></td></tr>" if @target.location.value.blank?
    html += "</table>"
%>
$('semantic').insert('<%= escape_javascript(html) %>');

我可以用浏览器清楚地浏览代码,但是最后一行给我带来了麻烦。它将html中的内容编码为html实体,我不想这样,因为这会破坏javascript。Fiddler中的响应如下所示:

$("语义").replace (");$("语义").insert (' & lt;表ajax类= '"'"祝辞& lt; tr> & lt; td>欧盟-27日& lt;/td> & lt; td> 28days & lt;/tr> & lt; tr> & lt; td> gb & lt; td>没有数据Available & lt;/tr> & lt; tr> & lt; td>美国Kingdom & lt; td>29days> & lt;/td> & lt;/tr> & lt;/table>);

如何防止页面对html变量进行编码?我试着用<%!html %>但是没有返回任何结果。

修复它,解决方案是

$('semantic').replace('<div id="semantic"></div>');
<%
    html = '<table class="ajax">'
    html += "<tr><td>EU - 27</td><td>#{@eu.value.value} days</td></tr>"
    html += "<tr><td>#{@source.location.value}</td><td>#{@source.value.value } days></td></tr>" unless @source.location.value.blank?
    html += "<tr><td>#{@cv.country.name}</td><td>No Data Available</td></tr>" if @source.location.value.blank?
    html += "<tr><td>#{@target.location.value}</td><td>#{@target.value.value } days></td></tr>" unless @target.location.value.blank?
    html += "<tr><td>#{@vacancy.country.name}</td><td>#{@target.value.value } days</td></tr>" if @target.location.value.blank?
    html += "</table>"
%>
$('semantic').insert('<%=raw html  -%>');

找到了解决方案:在动词模板中禁用HTML转义