So after missing the wisdom1 of this:
And responding to this:
http://b.lesseverything.com/2008/2/19/haml-doesn-t-like-javascript
I went to bed.
This morning I wrote my first Rails (really Haml) Monkey Patch2. This adds some of what Steve wanted: undisturbed inline javascript with variable interpolation. I am not sure what else he wanted as I did not read his blog carefully :)
Throw this into lib/inline_javascript.rb
1 module Haml 2 module Filters 3 class InlineJavascript 4 HEAD =<<EOH 5 <script type="text/javascript"> 6 //<![CDATA[ 7 EOH 8 9 FOOT =<<EOF 10 //]]> 11 </script> 12 EOF 13 14 def initialize(text) 15 @text = HEAD + text + FOOT 16 end 17 18 def render 19 @text 20 end 21 end 22 end 23 24 module Precompiler 25 def close_filtered(filter) 26 @flat_spaces = -1 27 filtered = filter.new(@filter_buffer).render 28 29 if filter == Haml::Filters::Preserve 30 push_silent("_hamlout.buffer << #{filtered.dump} << \"\\n\";") 31 elsif filter == Haml::Filters::InlineJavascript 32 # suppress eval option does not apply to us 33 flush_merged_text 34 js = unescape_interpolation(filtered) 35 @precompiled << "_hamlout.buffer << #{js};" 36 else 37 push_text(filtered.rstrip.gsub("\n", "\n#{' ' * @output_tabs}")) 38 end 39 40 @filter_buffer = nil 41 @template_tabs -= 1 42 end 43 end 44 end
Throw this at the bottom of your environment.rb, taken from here http://groups.google.com/group/haml/msg/2d890cf1ede761ea
1 require 'inline_javascript' 2 3 Haml::Template.options = { 4 :filters => { 5 'javascript' => Haml::Filters::InlineJavascript 6 } 7 }
And then do this in your Haml file:
1 :javascript 2 function oh_yea() { 3 alert('Hello' + '#{@message}') 4 } 5 %a{ :href =>"javascript:oh_yea()" } Oh Yea!
Update
I decided to make a patch and submit it to the Haml folks directly. This gave me the ‘opportunity’ to get git going.
Nathan Weizenbaum took the time to put in a more comprehensive fix to expose the interpolation functionality to all filters — look for it in an upcoming release.
1 It’s turtles all the way down.
2 You do not want to know what my subconscious originally thought up as the way to do this — that was twisted.