我正在构建一个 Rails 应用程序,它使用 Pusher 使用 Web 套接字将更新直接推送到客户端。在 JavaScript 中:
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
});
这很好,除了我在重复自己。mustache 模板与我已经编写的用于从服务器呈现 HTML 的 ERB 模板 99% 相同。mustache 和 ERB 模板的预期输出/目的是 100% 相同的:将推文对象转换为推文 html。
消除这种重复的最佳方法是什么?
更新:尽管我回答了自己的问题,但我真的很想看看其他人的其他想法/解决方案——因此是赏金!