html_safe 在我调用 truncate() 方法时不起作用

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

我有一个简单的 RSS 提要供我尝试建立的网站使用。我想为 post 阅读更多内容 link,并将输出限制为 300 个字符。我的代码如下所示:

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

无论出于何种原因,当我创建 post 时,即使我正在执行 html_safe,也会包含 html 标签。有任何想法吗?谢谢

truncate 自动将输出标记为 html_safe 并且默认情况下也会对内容进行转义。这意味着您的 link 可能在您自己将其标记为 html_safe 之前就已经被转义了。

您可以将 escape: false 选项传递给 truncate 以使其跳过默认情况下执行的转义。

例如

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

来自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).