In Rails, how can I allow some html in a text area?

…衆ロ難τιáo~ 提交于 2019-12-21 07:36:06

问题


I have a Rails app (blog) that I am creating. Very basic stuff. In my content area I have a text area for the content of the post. I am needing to include some html in the text area (links, formating, etc).

<%= f.text_area :content %>

Is there another tag that I can use instead of text_area, that will allow me to do this?


回答1:


Have you tried this in the views?

 <%= content.html_safe %>



回答2:


This is an old question but I guess there's a pretty straight forward view helper for this: sanitize. I presume you'd want to render the HTML tags entered by the user. For that purpose, save the content as a string and render as HTML using sanitize.

Example usage:

sanitize @post, tags: %w(strong em a code pre h2 h3 p blockquote ul ol li br),
                attributes: %w(href class)

The tags option allows you to specify which tags to use and same with the html attributes.




回答3:


The HTML safe method is actually .html_safe. Just tested on a text field.

For example:

<%= @item.description.html_safe %>



回答4:


Are you looking for something similar to the bold, italic, ... options you get when posting in stackoverflow? If so, I would suggest Markitup, a text-editor plugin for jQuery. Once you get this set-up, you'll be able to enter mark up in your text area (e.g. Markdown, bbcode, ...). When you actually display the result on the page, you simply need to have Ruby parse the mark up language you chose.

E.g.

<%= @user.bio.bb_code %>

Using this method, you allow your users enter styled text in a safe fashion.




回答5:


With the forthcoming Rails 6, you will be able to use a new rich_text_area tag to create a rich text editor in your forms like this:

<%= form_with(model: article) do |f| %>
  <div class="field">
    <%= f.label :content %>
    <%= f.rich_text_area :content %>
  </div>
<% end %>

See Action Text Rails Guide




回答6:


text_area_tag is probably what you want.



来源:https://stackoverflow.com/questions/2831072/in-rails-how-can-i-allow-some-html-in-a-text-area

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!