12

I am using backbone.js on a rails backend with HAML Coffee, which is compiled by haml_coffee_assets. There is some duplication in my templates.

Is there a way to create rails-like partials to dry up my templates?

Addition: Can I do content_for(:something) in Coffee HAML?

iblue
  • 29,609
  • 19
  • 89
  • 128

1 Answers1

20

There is no content_for helper in Haml Coffee, but you simply can render another template within a template.

Without Local Variables

For example, you've a template test:

%p My Partial
%ul
  %li Is included

You can include it within another template like this:

%p Another template
!= JST['test']()
%p That includes a partial

The trick is to unescape the rendered HTML with !=.

With Local Variables

To pass local variables, just send them to the JST function. If this is your partial (articles/_comments.jst.hamlc):

%h2=@title
%p=@content

Then this may be your template:

%h1 Comments for this article
- for comment in @article.comments 
  != JST['articles/_comment'](comment)
iblue
  • 29,609
  • 19
  • 89
  • 128
Netzpirat
  • 5,481
  • 1
  • 22
  • 21
  • Thank you! Can you add how to do local variables? Is there a way to emulate `content_for()` or do anything like that? I have a menu bar in my parent template and I want to fill in the buttons from the included partial. – iblue Feb 08 '12 at 22:58
  • Found out the local variable thingy myself and edited your post. Still no idea how to do content_for. – iblue Feb 09 '12 at 12:37
  • 4
    You can define a global context for your Haml Coffee assets, which can also contain a function. So you can mix in something like `{ content_for: (name, context = @) -> JST[name](context) }`, so you can use `@content_for('articles/comment')` It's described the Haml Coffee Readme who to define a global context. – Netzpirat Feb 15 '12 at 23:55
  • 1
    To add to @Netzpirat's answer I use the `render_partial` helper I found [here on stackoverflow](http://stackoverflow.com/a/11131433/376680) and it works great. It is pretty much the same as @Netzpirat's code but with added sugar and support for underscore leading partial file names. Sorry, no `content_for`, thought it might be helpful though :) – mraaroncruz Oct 03 '12 at 15:46