开发者

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

I've searched the web for a while looking for a tutorial, but haven't had much luck开发者_Go百科.

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜