0
votes

Note: This is a very strange and unique use case so I apologise in advance if it seems a bit ass-backwards.

I have a haml file content.haml and a coffeescript file main.coffee. I wish to somehow get the html resulting from rendering content.haml into a variable in the coffeescript/resulting javascript.

The end result should be a javascript file rendered to the browser.

let's say they look like this:

# content.haml
.container
  .some_content
    blah blah blah

-

# main.coffee
html_content = ???
do_something_with_html_content(html_content)

I know, this sounds ridiculous, 'use templates', 'fetch the HTML via ajax' etc. In this instance however, it's not possible, everything needs to be served via one JS file and I cannot fetch other resources from the server. Weird, I know.

Short of manually reconstructing the haml in the coffeescript file by joining an array of strings like this:

html_content = [
  '<div class"container">',
    '<div class"some_content">',
      'blah blah blah',
    '</div>',
  '</div>',
]

I'm not sure the best way of doing this.

Another way I though of was to put something like this in the coffee file:

html_content = '###CONTENT###'

Then render the haml to html in ruby, render the coffeescript to js and then replace ###CONTENT### with the rendered html before serving to the client. However the html is a multi-line string so it completely destroys the javascript.

I'm convinced there must be some other nice way of rendering the haml into html in a variable such that it forms valid javascript, but my brain has gone blank.

3
Can you put your coffeescript code inside HAML or it has to stay seperate in a different file? - Jasdeep Singh
It doesn't matter so long as the result is a JS file rendered to the client. I hadn't thought of it the other way around but I'm not sure how that would work? - Pete Hamilton

3 Answers

0
votes

Perhaps you can try something like this in one of your views:

:javascript
   html_content = <%= escape_javascript(render partial: "content")%>
   ## your own logic follows here....
0
votes

Wouldn't it be better to use a custom html data attribute and then fetch the content of it in js?

<div data-mycontent="YOUR CONTENT GOES HERE"></div>

And then in coffee, use the dataset attribute / data via jquery, if it is available.

If you set a var via writing the file directly it will render your js file uncacheable, among other drawbacks.

0
votes

You can do that by using the sprockets gem, like Rails does. You just need to rename your CoffeeScript file to main.coffee.erb and use it as you would e.g. a haml template. Pass in your rendered html with an instance variable:

html_content = '<%= @html_content %>'

Edit: Added missing quotes.