Live preview of formatted HTML form input with Rails

我是研究僧i 提交于 2019-12-23 03:29:08

问题


I want a feature of previewing some text with HTML tags and then storing the text in database. I know it is not a good idea to allow HTML in database, for XSS security reasons. What are the ways to achieve this?

I want a feature similar to the one we have in stackoverflow, where we can format our sourcecodes. Thanks.


回答1:


Recommended way:

Create an javascript event listener for the form on your html-page. Submit the input via ajax to your rails app, where the input gets rendered (for example by the same helper that will later render the output from the database).

Use a markup language like RedCloth/Textile to avoid XSS. It's also easier to type/understand for your users!

Your requested way:

Create an javascript event listener and write the contents of the form/input to another div.

The javascript you'll need depends on which library you use (Prototype or jQuery, for example).

Example:

Suppose you have a form with a textarea, <textarea id="text"></textarea>, and a preview area div with <div id="preview"></div> and you are using Prototype:

document.observe("dom:loaded", function() {
  new Form.Element.Observer('text', 0.25, 
    function () {
      $('preview').update($F('text'));
    }
  );
}

This will check the textarea every 250ms for changes and copy its input into the preview div.

Actually, you just need the code inside the function that is called with document.observe (starting with new Form.Element.Observer.... The document.observe will call this code after the browser has finished building the DOM-tree.




回答2:


You could also consider using something like textile or markdown, which are ways to achieve HTML markup with plain text.



来源:https://stackoverflow.com/questions/5475862/live-preview-of-formatted-html-form-input-with-rails

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