i62phq
Last Updated: February 25, 2016
·
6.065K
· tomaszborowski
Avatar

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
Respond

3 Responses
Add your response

13118
8b4691e426e23289f6bd173203c4ab34

OMG! This saved my life.

over 1 year ago ·
17857
None

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 ·
23540
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 ·