[英]Why will my string only work when I put it in manually?
Here is the exact string that is stored in the db: 这是存储在数据库中的确切字符串:
@blog_post.content = "<p><img src=\"http://localhost:3000/assets/sa_clubbing_logo.png\" alt=\"Sa_clubbing_logo\"><div><b>An image</b></div><div><b><br></b></div><div><b>Another image</b></div><div><b><img src=\"http://localhost:3000/assets/sa_clubbing_logo.png\" alt=\"Sa_clubbing_logo\"><br></b></div></p>"
as you can see. 如你看到的。 It is made up of a few images and some bold text. 它由一些图像和一些粗体文本组成。
Ok, so I have html saved in the db. 好的,所以我将html保存在数据库中。 I am trying to append the html to a content editable div (my rich text editor) like this. 我试图将html附加到这样的内容可编辑div(我的RTF编辑器)上。
$(document).ready(function(){
$('#rte').append("<%= @blog_post.content %>");
});
It is showing up in my content editable div, but as actual text. 它显示在我的内容可编辑div中,但显示为实际文本。 I want it to be rendered as html so the images are actually showing. 我希望将其呈现为html,以便实际显示图像。 It seems like the html that is being appended is this: 似乎要附加的html是这样的:
<p><p><img src="http://localhost:3000/assets/sa_clubbing_logo.png" alt="Sa_clubbing_logo"><div><b>An image</b></div><div><b><br></b></div><div><b>Another image</b></div><div><b><img src="http://localhost:3000/assets/sa_clubbing_logo.png" alt="Sa_clubbing_logo"><br></b></div></p></p>
So I tried putting the string into the append method manually and I got exactly what I wanted: 因此,我尝试手动将字符串放入append方法,然后得到了我想要的:
$(document).ready(function(){
$('#rte').append("<p><img src=\"http://localhost:3000/assets/sa_clubbing_logo.png\" alt=\"Sa_clubbing_logo\"><div><b>An image</b></div><div><b><br></b></div><div><b>Another image</b></div><div><b><img src=\"http://localhost:3000/assets/sa_clubbing_logo.png\" alt=\"Sa_clubbing_logo\"><br></b></div></p>");
});
The html being appended here is this: 此处附加的html是这样的:
<p><img src="http://localhost:3000/assets/sa_clubbing_logo.png" alt="Sa_clubbing_logo"></p><div><b>An image</b></div><div><b><br></b></div><div><b>Another image</b></div><div><b><img src="http://localhost:3000/assets/sa_clubbing_logo.png" alt="Sa_clubbing_logo"><br></b></div><p></p>
The images are showing up in my editor just the way I imagined they should. 图像以我想象的方式显示在编辑器中。
Why does this work when I insert the string manually, but not when I use <%= @blog_posts.content %>
? 为什么当我手动插入字符串而不是使用<%= @blog_posts.content %>
?
I must be missing some sort of formatting issue here. 我一定在这里缺少某种格式问题。
Replace: 更换:
<%= @blog_post.content %>
With: 带有:
<%=raw @blog_post.content %>
Or: 要么:
<%== @blog_post.content %>
Or even: 甚至:
<%= @blog_post.content.html_safe %>
Explanation: 说明:
Rails protects you by default so you have to tell when you consider html safe. Rails默认情况下会保护您,因此您必须告诉何时考虑html安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.