0

我正在写一个博客,作为一种形式,我wysiwyg使用froala editor. 我还缩短了索引页面上的帖子内容,我使用truncate它的方法。问题是该.html_safe方法(应该将编辑表单中的内容显示html为纯文本而不是代码)不能与truncate方法串联工作。所以,这里是代码:

index.html.erb

<% @posts.each do |post| %>
    <h3 class="title">
        <%= post.title %>
        <small class="date">
            | <%= post.created_at.strftime('%B, %d, %Y') %>
        </small>
   </h3>
   <p class="fr-view">
       <%= truncate(post.content, length: 100).html_safe %>...
       <%= link_to ' Read more', post %>
   </p>
<% end %>

_form.html.erb

<%= form_for @post, role:"form" do |f| %>
    <p>
        <%= f.label :title %><br>
        <%= f.text_field :title %>
    </p>
    <div class="form-group">
        <%= f.label :content %><br>
        <%= f.text_area :content, id:"edit", rows:"3", class:"form-control" %>
    </div>
    <p>
        <%= f.submit 'Create', class:'btn btn-primary' %>
    </p>
<% end %>
<script>
  $(function() {
    $('#edit').froalaEditor()
  });
</script>

这就是post.contentin 控制台返回的内容:

Post.find(1)
     <Post id: 1, title: "Lorem Ipsum", content: "<p>Lorem ipsum dolor sit amet, consectetur adipisc..."
4

1 回答 1

1

问题是您颠倒了顺序。html_safe将字符串标记为受信任,但如果您随后对其进行其他操作,则它不再受信任。这应该有效:

<p class="fr-view">
    <%= truncate(post.content, length: 100).html_safe %>
</p>

更新:在评论中讨论这个问题后,我认为问题是如果你截断,一些标签可能会保持打开状态,这可能会在你的页面中产生各种问题(不一定限于字符串的内容)。几个选项:

  1. 不要截断字符串,而是用 CSS 限制显示的部分;在这种情况下,您仍将拥有有效的 HTML 代码,该代码应在浏览器中正确呈现;
  2. 在截断之前剥离所有 HTML 标记,如下所示:truncate strip_tags(post.content), length: 100. 这也将更加安全,因为您的用户可能会插入恶意代码。

作为一般说明,在 Rails 中使用sanitize代替是一种很好的做法html_safe,以降低向浏览器发送用户输入的恶意代码的风险。

于 2016-04-27T07:59:51.467 回答