HAML Having Multiple Lines While Using content_for, for JavaScript
Asked Answered
S

2

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.

Sculptress answered 30/12, 2011 at 1:25 Comment(0)
D
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)
Donnelly answered 30/12, 2011 at 1:33 Comment(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 <script><[cdata around the code. It works for me. For now anyways! Just making a note. Thanks for the help.Sculptress
S
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"); / }); / });

Slim answered 12/3, 2014 at 14:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.