html_safe doesn't work when I call truncate() method

849 views Asked by At

I have a simple RSS feed for a website I'm trying to build. I want to do a read more link for posts and limit the output to 300 characters. My code looks like this:

<p id="notice"><%= notice %></p>


<h1 class="reviews">What They're Saying About Us</h1>
<br />
<h1 class="post-title"><%= image_tag("icons8-rss-40.png") %>RSS Feed</h1>

  <% @home_blogs.each do |p| %>
    <div class="blog-posts">
      <h3><%= p.name %></h3> | <%= p.created_at.to_date %>
      <br />
      <p id="blog_post_content">
        <% if p.entry.length > 200 %>
          <%= truncate(p.entry, length: 300).html_safe %>
          <%= link_to "...read more", p %>
        <% else %>
          <%= p.entry.html_safe %>
      </p>
      <% end %>
      <br />
      <%= image_tag("if__hashtag_2559811.png")%>Tag Cloud
      <div class="tag-cloud">
      </div>
    </div>
  <% end %>

<span class="pagination"><%= will_paginate @home_blogs %></span>
<br>

For whatever reason the html tags are included when I create a post even though I'm doing html_safe. Any ideas? Thanks

1

There are 1 answers

1
Shadwell On BEST ANSWER

truncate automatically marks the output as html_safe and also escapes the content by default. This means your link is probably being escaped before you even get a chance to mark it as html_safe yourself.

You can pass an escape: false option to truncate in order to get it to skip the escaping that it does by default.

E.g.

<%= truncate(p.entry, length: 300, escape: false) %>

From the docs for truncate

The result is marked as HTML-safe, but it is escaped by default, unless :escape is false. Care should be taken if text contains HTML tags or entities, because truncation may produce invalid HTML (such as unbalanced or incomplete tags).