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 %>
Written by Tomasz Borowski
Related protips
3 Responses
OMG! This saved my life.
Maybe yours specs are different, but I find this implementation cleaner: http://cerdiogenes.blogspot.com.br/2014/12/improved-how-to-render-coffeescript.html
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.