Last Updated: May 15, 2019
· 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/
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:

<% unless resource.valid? %>
`<%= raw(render("shared/form"))%>`
<% end %>

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:

over 1 year ago ·

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 ·