Best strategy to use HAML template with Backbone.js

后端 未结 8 1950
别那么骄傲
别那么骄傲 2021-01-29 23:23

Im getting into Backbone.js to structure the javascript code for my project and I love HAML for templating on the backend(rails), so Id like to use it for Backbone Views templat

8条回答
  •  不知归路
    2021-01-29 23:34

    I've been working on Rails 3/Backbone app and have taken a different approach after evaluating hamlbars, haml_assets, and playing around with haml-js.

    These are all solid gems which offer solutions to the problem, each having a certain set of trade-offs. Haml-js, for instance, requires rendering templates client side (there's nothing wrong with this, it's simply a tradeoff). Hamlbars and haml_assets both plug into the asset pipeline but because they exist outside of the request object some helpers will not work. Both make some adjustments for this and include url helpers and ActionView helpers, but don't expect to have the same features as writing haml in a view.

    My approach is somewhat bulky (I am planning on putting this into an engine) but it works well and easily replicable. It uses haml_assets when possible, but falls back on serving a template from a "templates" controller with a "show" action

    • Put your views in the view/templates/ directory
    • You can add a layout that renders this view into a JST function
    • You can specify the show action to return "application/javascript" as its content type
    • You have access to all helpers when writing templates
    • You can add script tags for "/template/whatever" that will render the whatever template, or use route globbing for better organized views.

    The benefit of this approach is that because your views are accessible from controllers, you have the option to render them as jst templates (via the templates controller) or via other controllers as partials. This would allow you to serve seo-friendly pages directly from url's (like /products/widgets/super-cool-widget) were users may get the cached templated /templates/widgets/super-cool-widget.

提交回复
热议问题