Rails Client side / Server side rendering using single template (handlebars or Mustache) with Sammy.js

心已入冬 提交于 2019-12-05 02:20:45

问题


I've searched the web for a while looking for a tutorial, but haven't had much luck.

From what I understand, Twitter is using a single Mustache.js template in rails to render from the server on first page load, and then through their own ajax transition system (much like sammy.js).

I can get handlebars and sammy.js loaded in rails, but I can't figure out how to share a single template file from server(rails) & client(sammy) side.


回答1:


I have not personally built anything where I've used the same template server-side and client-side, but here is one way that I can think to do this.

Say you have an image partial (_image.mustache):

<div class="image">
  <a href="{{ view_url }}">
    <img height="{{ height }}" width="{{ width }}" src="{{ src }}" />
  </a>
</div>

When you render your page server-side you can just use this as a normal partial and interpolate it for Mustache. Then you can also render it in a script tag to use a Resig micro-templating scheme.

{{{image_js_template}}}

In your Mustache view class:

def image_js_template
  content_tag :script, :type => "template", :id => "image-template" do
    render :text => self.partial('image')
  end
end

This should render the template uninterpolated (with the {{'s still in the text). Now you can just pick up this template in your Javascript by it's id. In backbone.js you could do something like:

class Views.AllImageList extends Backbone.View
  initialize: (options) ->
    @template = $('#image-template').html()

I've not used Sammy.js but it appears that it expects all of it's templates to be publicly available, which could present an issue. However, you can still use the technique above and pass render() and partial() jQuery objects directly (as indicated here).

This is the basic idea, but there is probably a lot you could do to make this more seamless. I would checkout the Jammit section on using templates, specifically the part about using Mustache. Also ICanHaz.js has a way of simplifying the use of client side Mustache templates.



来源:https://stackoverflow.com/questions/5478654/rails-client-side-server-side-rendering-using-single-template-handlebars-or-m

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