我只需要自己处理这个问题。正如 Geoff 和 Andy 所提到的,您有 2 个选择:
- 使用 JavaScript 解析纺织品并使用 jquery 将其粘贴到您的页面中
- 使用 Ajax 调用从服务器获取解析的纺织品并使用 jquery 将其粘贴到页面中
我正在使用 http://github.com/aaronchi/jrails 将 scriptactulous 替换为 jquery,这让事情变得更容易一些。
这是我所做的:
我决定实施选项 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 中执行此操作,您需要在 environment.rb 中 gem.config 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 在客户端处理纺织品。