html - 在 Rails ERB 中混合 HTML 和非 HTML 字符串

标签 html ruby-on-rails ruby erb

我有一个文本区域,一些用户可以在其中输入 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: !&lt;/p&gt;
&lt;p&gt;Hello, dear Mr. X, new announcement;/p&gt;
&lt;h2&gt;The project&lt;/h2&gt;
&lt;p&gt;Blablabla&lt;/p&gt;
...
</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/

相关文章:

ruby-on-rails - 问题是由于 "accepts_nested_attributes_for"和 "has_many through"关系而发生的,它给出了 not id found error with factory_girl 和 rspec

ruby-on-rails - 从 Active Admin 过滤器向 Ransack 发送参数

ruby-on-rails - 引用连接 Rails 表中枚举的查询

ruby-on-rails - 如何使用 YARD 记录 Rake 任务?

javascript - 使用jquery动态添加类

html - 如何更改事件链接的颜色?

javascript - Bootstrap 导航的背景颜色在事件时不会改变?

mysql - 合并 View 中多个 Rails 表的数据

html - 主体图像与主容器保持一致

jquery - 使用 JQuery 和 Rails 生成链接预览