简体   繁体   中英

How to escape javascript-generated html in Rails?

On one side of my page, I have a very simple email form. On the other side I have a preview of the proposed email. For example:

在此处输入图片说明

As the user completes the fields, I'd like to update the preview on keyup. I wrote a little js function to do just that:

var email_previewer = function() {
  var fields = [
    { input: $('input#editor_invitation_to'), preview: $('dt.to') },
    { input: $('#editor_invitation_message'), preview: $('#message') }
  ];

  var perserve_linebreaks = function(text) {
    var html = text.replace(/\r\n\r\n/g, "</p><p>"),
      html = html.replace(/\r\n/g, "<br />"),
      html = html.replace(/\n\n/g, "</p><p>"),
      html = html.replace(/\n/g, "<br />"),
      html = "<p>"+html+"</p>";
    return html;
  };

  var sync_text = function(input, preview) {
    var text = input.val();
    if (input.is('textarea')) {
      text = perserve_linebreaks(text);
    }
    preview.text(text);
  }

  // sync preview on page load
  $.each(fields, function(index, field) {
    sync_text(field.input, field.preview);
  });

  // create keyup events
  $.each(fields, function(index, field) {
    field.input.keyup(function() {
      sync_text(field.input, field.preview);
    });
  });

}();

Everything works great except rails wants to escape my html and make it look like crap:

在此处输入图片说明

Normally, I know this is no problem: just add raw or html_safe . But I can't do that here since the markup is being dynamically built on keyup (or page load). Am I missing some simple solution? Any ideas for a workaround? My only idea is to load the preview in an iframe, which seems totally weird.

This is ridiculously frustrating. Someone please help!

I would immediately suspect preview.text(text) in your sync_text function. That should be creating a text node in the DOM, and what you want is to set the innerHTML so several nodes get created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM