简体   繁体   中英

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. I am trying to append the html to a content editable div (my rich text editor) like this.

  $(document).ready(function(){  

  $('#rte').append("<%= @blog_post.content %>");

  });

It is showing up in my content editable div, but as actual text. I want it to be rendered as html so the images are actually showing. It seems like the html that is being appended is this:

<p>&lt;p&gt;&lt;img src="http://localhost:3000/assets/sa_clubbing_logo.png" alt="Sa_clubbing_logo"&gt;&lt;div&gt;&lt;b&gt;An image&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;br&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Another image&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;img src="http://localhost:3000/assets/sa_clubbing_logo.png" alt="Sa_clubbing_logo"&gt;&lt;br&gt;&lt;/b&gt;&lt;/div&gt;&lt;/p&gt;</p>

So I tried putting the string into the append method manually and I got exactly what I wanted:

  $(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:

<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 %> ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM