gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:22:25 25 4
gpt4 key购买 nike

我有一个文本区域,一些用户可以在其中输入 HTML(请不要评论这是不安全的,我已经有 sanitizer 对策)。

现在,我想展示一个我的用户可以编写的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com