rails 3 and haml and unobtrusive javascript

I have created a Rails3 application, started with Haml/Sass and finding it awesome. I am also trying to do unobtrusive javascript. Before, in Rails 2.3, I would have expected a remote-form to have an :update attribute, where you could specify a selector where the response of the remote method would be rendered. Now it needs to be done differently: my controller function will render a ".js" view, which will do the necessary actions itself. This makes it more library agnostic, and i prefer jquery. So for instance i have a controller action "search", and i have a corresponding "search.js.erb" as follows: [ruby] $('.grid').replaceWith('<%= escape_javascript(render :partial => 'list') %>') [/ruby] This works. It will replace the html of the element with a class grid with the html from my rendered partial. I started out trying to achieve that in HAML, and failed at first. So first i created the above ERB code which worked. Now my task seemed simpler: translate this seemingly simple line to HAML. My first naive approach was to do the following: [ruby] = "$('.grid').replaceWith('#{escape_javascript(render :partial => 'list')}')" [/ruby] But this just places the html as a readable string inside my page. Even i do something simple like [ruby] = "$('.grid').replaceWith('<h3>Text</h3>') [/ruby] i see the actual characters [ruby] <h3>Text</h3> [/ruby] and not the markup. But i need to contain the javascript inside the double-quotes or haml will not recognise it, and can not interpolate my ruby there. After looking through the HAML reference, actually the solution was incredible simple. Once more. [ruby] != "$('.grid').replaceWith('#{escape_javascript(render :partial => 'list')}')" [/ruby] The != unescapes HTML (as opposed to the standard =). This is exactly what we need of course.
Konstantinos Pachnis 2010-09-30 11:10:41 UTC

Thanks for the tip.

ketan 2010-12-20 13:15:52 UTC

wow nice i like it

Bogdan Kulbida 2011-02-14 10:10:32 UTC

Really Great article. Thanks!

ayupmeduck 2011-05-23 12:32:22 UTC

Thanks, that was a bit tricky to work out. I was surprised to see that ruby interpolation also works, so you can do something like: != "$('#{@element_id}').replaceWith('#...etc This works even though the ruby is surrounded by single quotes, though I don't understand why that should be.

Bash 2012-03-17 21:57:48 UTC

Thanks for this! Very helpful.

Teddy 2012-07-05 19:27:33 UTC

You can also use the :plain tag in haml: :plain $(‘#{@element_id}’).replaceWith(‘#…etc

Add comment

Recent comments