Last Updated: February 25, 2016
· tomaszborowski

How to render coffeescript partial inside coffeescript template

What if you want to organize coffescripts into partials so they could be reused in your Rails app? Problem may occur when you try to render one coffescript file within another. Coffeescipt files are compiled to pure Javascript before rendering. For example, if coffeescript partial defines some function, then SyntaxError: Reserved word “function” will be raised.

Let’s assume that we have coffescript partial:

# shared/_form.js.coffee:
makeAlert = (message) -> alert(message)

Then to render it in another coffeescript we have to use backticks to embed pure javascript code. Here is an example of coffee template which loads another coffee partial:

# create.js.coffee:
<% unless resource.valid? %>
`<%= raw(render("shared/form"))%>`
<% end %>
Say Thanks

3 Responses
Add your response


OMG! This saved my life.

over 1 year ago ·

Maybe yours specs are different, but I find this implementation cleaner: http://cerdiogenes.blogspot.com.br/2014/12/improved-how-to-render-coffeescript.html

over 1 year ago ·
11087955 975335272491654 1100908472169072458 o

If you have arrived here from google and saw that the original solutions works. Try out the one from cerdiogenes its output is a bit nicer.

over 1 year ago ·