6

我在使用 Rails 的许多 WYSIWYG gems/plugins 时遇到了问题,所以我自己使用 RedCloth gem 构建了一个。我希望用户在填写表单时看到他们的 HTML 格式文本的实时预览,但不知道如何使用 jQuery 和 RedCloth 来做到这一点。这是我在 application.js 中尝试的:

$('#comment').keyup(function(){
  var formatted = RedCloth.new($(this).val()).to_html;
  $('#preview').html(formatted);
});

这不起作用并不奇怪,因为 RedCloth.new 可能无法在 .js 文件中执行,但不知道如何动态格式化文本。

4

2 回答 2

4

我只需要自己处理这个问题。正如 Geoff & Andy 提到的,你有 2 个选择:

  1. 使用 JavaScript 解析纺织品并使用 jquery 将其粘贴到您的页面中
  2. 使用 Ajax 调用从服务器获取解析的纺织品并使用 jquery 将其粘贴到页面中

我正在使用http://github.com/aaronchi/jrails用 jquery 替换 scriptactulous,这让事情变得更容易一些。

这是我所做的:

我决定实施选项 2,因为获得与通过 RedCloth 显示的格式完全相同的格式对于我的应用程序至关重要。

我在我的页面中添加了以下内容<head>

<script>
var timeStamp1 = -1;
var timeStampSent1 = -1;
function delay() {
    setTimeout('preview()',1000);
}
function preview() {
    var n = new Date().getTime();
    // Ask for update if textarea was changed since this function last ran
    if (timeStamp1 != -1 && timeStamp1 != timeStampSent1) {
        $.post('/whatevers/ajax_update_preview', $('#textile').serialize(), null, "script");
        timeStampSent1 = timeStamp1;
    }
    delay(); // Run this again in 1000ms
}

// Important for letting you send ajax requests with jquery & rails
jQuery.ajaxSetup({  
    'beforeSend': function (xhr) {xhr.setRequestHeader("Accept", "text/javascript")}  
});


$(document).ready(function(){
    // Event binding to watch for changes to the textarea
    $('#textile').keydown(function() {
      timeStamp1 = event.timeStamp
    });
});
</script>

<body>你显然需要:

<textarea id="textile" name="some_text"></textarea>
<div id="preview"></div>

您的控制器中需要以下内容:

class WhateversController < ApplicationController
  def ajax_update_preview
    txt = params[:some_text]
    render :update do |page|
      page.replace_html 'preview', :partial => 'preview', :object => txt
    end
  end

部分(_preview.html.haml;它在 HAML 中,因为这是我使用的,但您也可以在 ERB 中执行此操作,并且您需要 gem.config 在 environment.rb 中配置 RedCloth gem):

- if live_textile_preview
  = RedCloth.new(live_textile_preview).to_html

最后,记得把它放在你的 routes.rb 中:

map.resources :whatevers, :collection => {:ajax_update_preview => :post}

我对 javascript 非常缺乏经验(我只是将一些东西放在一起),所以我确信这里的 JS 可以改进。

请注意,如果您同时拥有大量用户,这会对服务器资源造成重大影响。如果是这种情况,您最好使用 javascript 在客户端处理纺织品。

于 2010-09-30T17:26:01.960 回答
0

我认为您将需要在 javascript 中执行此操作,除非您想对 keyup 事件或类似的东西进行 ajax 调用。

这个链接有一些很好的资源:Markdown、Textile 和其他的 JavaScript 库;锚参考

于 2010-08-16T23:56:28.973 回答