开发者

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:

How to escape javascript-generated html in Rails?

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:

How to escape javascript-generated html in Rails?

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 id开发者_运维百科eas 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜