简体   繁体   English

如何在Rails中转义javascript生成的html?

[英]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. 当用户填写字段时,我想更新keyup上的预览。 I wrote a little js function to do just that: 我写了一个小js函数来做到这一点:

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: 一切工作都很好,除了Rails想要转义我的html并使它看起来像废话一样:

在此处输入图片说明

Normally, I know this is no problem: just add raw or html_safe . 通常,我知道这没有问题:只需添加rawhtml_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. 我唯一的想法是将预览加载到iframe中,这似乎很奇怪。

This is ridiculously frustrating. 这简直令人沮丧。 Someone please help! 有人请帮忙!

I would immediately suspect preview.text(text) in your sync_text function. 我会立即怀疑您的sync_text函数中的preview.text(text) That should be creating a text node in the DOM, and what you want is to set the innerHTML so several nodes get created. 那应该是在DOM中创建一个文本节点,而您想要设置的是innerHTML以便创建多个节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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