【问题标题】:Rails Client side / Server side rendering using single template (handlebars or Mustache) with Sammy.jsRails 客户端/服务器端渲染使用单个模板(车把或 Mustache)和 Sammy.js
【发布时间】:2011-03-29 20:40:22
【问题描述】:

我在网上搜索了一段时间以寻找教程,但运气不佳。

据我了解,Twitter 使用 Rails 中的单个 Mustache.js 模板在第一页加载时从服务器呈现,然后通过他们自己的 ajax 转换系统(很像 sammy.js)。

我可以在 rails 中加载把手和 sammy.js,但我不知道如何从服务器(rails)和客户端(sammy)端共享单个模板文件。

【问题讨论】:

    标签: ruby-on-rails mustache sammy.js


    【解决方案1】:

    我没有亲自构建任何使用相同模板服务器端和客户端的东西,但这是我能想到的一种方法。

    假设你有一个图像部分(_image.mustache):

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

    当您在服务器端渲染页面时,您可以将其用作正常的部分并将其插入到 Mustache 中。然后你也可以在脚本标签中渲染它以使用Resig micro-templating scheme

    {{{image_js_template}}}
    

    在您的 Mustache 视图类中:

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

    这应该呈现未插值的模板({{ 仍在文本中)。现在你可以通过它的 id 在你的 Javascript 中选择这个模板。在backbone.js 中,您可以执行以下操作:

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

    我没有使用过 Sammy.js,但它似乎希望它的所有模板都是公开可用的,这可能会带来问题。但是,您仍然可以使用上述技术并直接传递 render() 和 partial() jQuery 对象(如 here 所示)。

    这是基本的想法,但您可能还可以做很多事情来使其更加无缝。我会查看the Jammit section on using templates,特别是关于使用 Mustache 的部分。 ICanHaz.js 还可以简化客户端 Mustache 模板的使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      相关资源
      最近更新 更多