我有一个文本区域,一些用户可以在其中输入 HTML(请不要评论这不安全,我已经有了清理对策)。
现在,我想展示一个用户可以编写的 html 代码示例。如何使用 ruby 在 .erb 模板文件中执行此操作?
最终用户的视觉输出应如下所示(没有语法突出显示,请遵守换行符!)
my_example_string
:
Here is an example of sample code you can write in the text-area:
<p>Hello, dear Mr. X, new announcement</p>
<br>
<h2>The project</h2>
<p>blablabla</p>
<h2>Your role</h2>
<p>...</p>
编辑:实际的 HTML 输出看起来像
<p>
Here is an example of sample code you can write in the text-area: !</p>
<p>Hello, dear Mr. X, new announcement;/p>
<h2>The project</h2>
<p>Blablabla</p>
...
</p>
我尝试过类似的方法
<%= 'Here is an example of sample code you can write in the text-area:' +'<br>'.html_safe +
'<br>' + '<br>'.html_safe +
'<p>Hello, dear Mr. X, new announcement</p>'+'<br>'.html_safe +
'<h2>The project'</h2>' + ... %>
但是输出看起来像(一行)
Here is an example of sample code you can write in the text-area:<br><br><br><p>Hello, dear Mr. X, new announcement</p><br><h2>The project</h2>
显然我不能混合 .html_safe
和非 .html_safe
字符串
有什么想法吗?
编辑 2:
我实际上使用的是自定义帮助器/渲染器,它将此伪工具提示 my_example_string
作为参数
my_view.html.erb
...
<%= render 'shared/field_with_tooltip',
field: f.text_area(:body, placeholder: '', class: 'form-control', value: (@body if @body)),
label: 'Body of the message',
info: my_example_string %>
我的field_with_tooltip
使用这样的信息变量
shared/field_with_tooltip.html.erb
...
<% if info %>
<p class="text-info field-info"><%= info %></p><br>
<% end %>
...
最佳答案
不需要使用 <
和 >
编写 HTML 实体本身,从而避免 Rails 完成这项工作:
<%= ('Here is an example of sample code you can write in the text-area:<br>' +
h('<br>') + '<br>' +
h('<p>Hello, dear Mr. X, new announcement</p>')+'<br>' +
h('<h2>The project</h2>') + ...).html_safe %>
这使用 html_escape
帮助器将要呈现的 HTML 转换为实体,然后您可以对整个结果字符串调用 html_safe
以避免通常使用 HTMLSafe 缓冲区遇到的问题。
我可能会通过完全避免 html_safe
并使用 Rails 的内置转义来清理它:
Here is an example of sample code you can write in the text-area:<br>
<%= '<br>' %><br>
<%= '<p>Hello, dear Mr. X, new announcement</p>' %><br>
<%= '<h2>The project</h2>' %>
后一种方法更加简洁。
关于html - 在 Rails ERB 中混合 HTML 和非 HTML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31613706/