我在构建一个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