8

I am trying to output some inline js on a page. I don't really want to add it to any JS file since it is so aribtrary and one time use. That being said, I am using haml and also trying to use content_for in order to place the JS after jquery is loaded from the layout.

The problem is that haml does not like multiline text that is indented (I think)

I am trying to do the following:

=content_for :javascript do
  $(function(){
    $("#sell_tickets_here").live("vclick",function(){
      if($(this).is("checked"))
        $("#tickets_here").display("inline");
      else
        $("#tickets_here").display("none");
    });
  });

In my layout I have:

  = yield(:javascript)

Which actually works if I only have 1 line after the content_for statement.

Parris
  • 17,833
  • 17
  • 90
  • 133

2 Answers2

16

The correct syntax would be:

- content_for :javascript do
  :javascript
    $(function(){
      $("#sell_tickets_here").live("vclick",function(){
        if($(this).is("checked"))
          $("#tickets_here").display("inline");
        else
          $("#tickets_here").display("none");
      }); 
    });

Notice the dash versus the equal sign and the :javascript HAML filter. HAML works just fine with multi-line as long as it is 2-space indented.

And then in the other part of your view:

= content_for(:javascript)
iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
  • 1
    Thanks this worked. The only thing to note is that if you have content for javascript coming from multiple pages it'll put in a script tag for each of them. the haml :javascript wraps – Parris Dec 30 '11 at 22:20
0

This is called escaping, and in this case you escape, ergh, indentation:

=content_for :javascript do / $(function(){ / $("#sell_tickets_here").live("vclick",function(){ / if($(this).is("checked")) / $("#tickets_here").display("inline"); / else / $("#tickets_here").display("none"); / }); / });

phil pirozhkov
  • 4,740
  • 2
  • 33
  • 40