如何在html中显示一些带有标签的文字?

问题描述 投票:0回答:1

我最近在学习rails,现在正在尝试使用Wysiwyg编辑器来编辑博客文章的正文,使用起来很不错,但是在通过Wyziwyg保存文字和表情符号后,我得到的文字和标签如下。我真正想要的是在Wysiwyg中显示我写的所有内容,包括表情符号,如下图。

我必须使用Wyswyg编辑器来显示这篇文章的正文吗?比如禁用编辑器功能?如果不是这样,我是否需要另一种宝石?

enter image description here下面是index.html.erb,如下图。

<div class="main">
    <section>
        <a href="<%= new_admin_post_path %>"><button class="create-button">Create New</button></a>
        <% if @posts.exists? %>
            <% @posts.each do |post| %>
                <article class="article-summary">
                    <h1 class="article-title"><%= post.title %></h1>
                    <div class="article-content"><%= truncate post.body, length: 200 %></div>
                    <p class="article-created-at"><%= post.created_at.to_time.strftime('%B %e at %l:%M %p') %></p>
                    <p class="article-command"><a href="<%= edit_admin_post_path(post) %>"><button>Edit</button></a> <%= link_to button_tag("Delete"), admin_post_path(post), method: :delete, data: { confirm: 'Are you sure?' } %></p>
                    <% if post.image.attached? %>
                        <%= image_tag post.image, class: "article-image" %>
                    <% else %>
                        <%= image_tag 'https://placekitten.com/1000/800', class: "article-image" %>
                    <% end %>
                </article>
            <% end %>
            <%= will_paginate @posts, class: "page"%>
        <% else %>
            <h2>There is no post</h2>
        <% end %>
    </section>
</div>
html ruby-on-rails wysiwyg
1个回答
1
投票

你可以使用 html_safesanitize 方法,将所见即所得的编辑器中的文本渲染成html页面。

使用 html_safe 可以是这样的。

@str = "<b>Hi</b>".html_safe
<%= @str %>

而利用 sanitize 使用 rails-html-sanitizer gem可以如下图所示。

full_sanitizer = Rails::Html::FullSanitizer.new
full_sanitizer.sanitize("<b>Bold</b> no more!  <a href='more.html'>See more here</a>...")

根据这两种方法的文档,很明显,使用 sanitize 是比较可靠的,建议使用。

建议你用sanitize代替这种方法。

简单的解决方案,使用 html_safe:

<%= post.body.html_safe %>

使用可靠的解决方案 sanitize: 此方法删除背景样式,因为它包含了 url 方法。所以,你需要定义自定义的css sanitizer。

© www.soinside.com 2019 - 2024. All rights reserved.