Mustache render on the server (rails) and on the client (javascript)

被刻印的时光 ゝ 提交于 2019-12-12 11:34:57

问题


Is there any documentation on Mustache best practices when using on the server (with rails) and on the client (with javascript)?

# hello_world.mustache
Hello {{planet}}

# some other file
<%
hello_world_template = File.read(File.dirname(__FILE__) + "/hello_world.mustache")
%>

<script id="hello_world_template" type="text/x-jquery-tmpl"> 
    <%= hello_world_template %>
</script>

<script>
    // $.mustache = using mustache.js and a jquery mustache wrapper 
    // search on "Shameless port of a shameless port"
    document.write($.mustache($("#hello_world_template").html(), { "planet" : "World!" }));
</script>

<%= Mustache.render(hello_world_template, :planet => "World!") %>

The above isn't scalable. I'd prefer not to make my own engine for this.

Is there a more complete templating engine that allows reuse of templates on the server and on the client?

Additionally, one that accounts for nested templates on the server and the client?


回答1:


There is Poirot available: Mustache + Rails 3.




回答2:


not familiar with the ruby on rails syntax but here is my take:

a) Why do you want to generate the markup on the server side at all (if at all that is an option) always send in json data to the client and let js mustache engine deal with it

b) if you still want to keep your server side rendering engine, then what you can do is keep all your mustache templates in a folder write a script that you execute during your build (or equivalent in ruby on rails) that combines all the templates into a nicely scoped JS file with the right naming conventions.

Something as follows:

var MUSTACHE_TEMPLATES= MUSTACHE_TEMPLATES || (function(){
var template1= "<big ass template>";
var template2="<small template>";

return
{
template1: template1,
template2: template2
}
}());

What do you think of that approach? Now you have your templates living in a single location and you also get the advantages of the js file being cached




回答3:


The stache gem seams to be what you need. Mustache or handlebars + Rails 3 or Rails 4



来源:https://stackoverflow.com/questions/7045656/mustache-render-on-the-server-rails-and-on-the-client-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!