Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared Rails and JavaScript views

I'm a little confused as to why this isn't a more commonly addressed problem but here goes.

I have my Rails app which generates my views normally. I have some dynamic content on the interface.

I want to make an AJAX call, return JSON, and populate the dynamic portions of the application. I would use a JS templating library to do this.

I DON'T want to make an AJAX call, have Rails process the view and send all the HTML back. I want the response to be JSON so cut down on processing and wire time.

The problem is that the HTML I'm generating dynamically is the same HTML I'm generating statically on page load by Rails (think AJAX pagination). The HTML is naturally in my ERB files. But when I generate more content (say, page 2), I obviously can't access the ERB files and need to duplicate the HTML in a JavaScript template file.

Is there a solution out there which allows me to share my views between Rails and JS? (I understand it's a little awkward to try to mix ERB with JS rendering...loops, conditionals, etc)

Do people usually settle for rendering HTML and sending it over the wire? Or, do they awkwardly execute JavaScript upon page load to render using JS templates?

like image 654
Mike Avatar asked Jun 16 '11 03:06

Mike


1 Answers

I ran into the same problem in the past. I was able to solve it with Mustache: http://mustache.github.com/ At the time there was no easy way to setup mustache with rails so I had to code something together. It looks like now there is a lib for it here: https://github.com/goodmike/mustache_rails3

Update: Looks like there is a nice gem now to accomplish it called stache: https://github.com/agoragames/stache

like image 194
Michal Kuklis Avatar answered Oct 18 '22 09:10

Michal Kuklis