我在構建一個Rails應用程序,該應用程序使用Pusher使用Web套接字將更新直接推送到客戶端。在javascript中:如何在使用Javascript和ERB模板時保持DRY(Rails)
channel.bind('tweet-create', function(tweet){ //when a tweet is created, execute the following code:
$('#timeline').append("<div class='tweet'><div class='tweeter'>"+tweet.username+"</div>"+tweet.status+"</div>");
});
這是令人討厭的代碼和演示混合。所以自然的解決方案是使用JavaScript模板。或許生態或鬍子:
//store this somewhere convenient, perhaps in the view folder:
tweet_view = "<div class='tweet'><div class='tweeter'>{{tweet.username}}</div>{{tweet.status}}</div>"
channel.bind('tweet-create', function(tweet){ //when a tweet is created, execute the following code:
$('#timeline').append(Mustache.to_html(tweet_view, tweet)); //much cleaner
});
這是很好的和所有,但,我重複自己。小鬍子模板與我已經編寫用於從服務器呈現HTML的ERB模板99%相同。鬍子和ERB模板的預期輸出/目的是100%相同的:將tweet對象變成tweet html。
消除這種重複的最佳方法是什麼?
更新:儘管我回答了我自己的問題,但我真的很想看到其他人的想法/解決方案 - 因此是賞金!
供將來參考:Mustache(您已經提到過)也允許進行服務器端渲染(請參閱http://mustache.github.com/中的實現)。流程現在變爲:1使用mustache-template進行初始服務器端渲染+使用完全相同的mustache-template連續N次客戶端渲染 – 2011-07-26 09:31:53
非常感謝。我會看看那些。 – user94154 2011-07-26 17:35:46
fyi:剛纔我問了一個類似的問題(尋找可以替代限制小鬍子的選項),儘管流程會保持不變。也許這也有幫助。請參閱:http://stackoverflow.com/questions/6831718/client-side-templating-language-with-java-compiler-as-well-dry-templating – 2011-07-26 18:29:21