Javascript in Haml

by Melvin Ram

One thing that is not obvious with HAML is how to add javascript. In the past, haml didn’t really like javascript that much but the latest version of haml on github makes it very simple. It’s done using the :javascript filter. Here’s an example:

:javascript
  jQuery(function(){
    tog("#forgot_password_clicker", "#login_form");
    tog("#forgot_password_clicker", "#forgot_form", forgot_text);
  });

You can also mix in ruby variables by using the standard way of interpolating ruby with strings through: #{ }. Here’s an example of how it all works in a full page with a ruby variable mixed in:

!!! XML
!!!
%html{:xmlns => "http://www.w3.org/1999/xhtml", "xml:lang" => "en", :lang => "en"}
  %head
    %meta{'http-equiv' => "content-type", :content => "text/html;charset=UTF-8"}

  %body
    - @some_ruby_variable = "something goes here."
    :javascript
      #{@some_ruby_variable}
      jQuery(function(){
        tog("#forgot_password_clicker", "#login_form");
        tog("#forgot_password_clicker", "#forgot_form", forgot_text);
      });

This makes this HTML:

<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang='en' xml:lang='en' xmlns='http://www.w3.org/1999/xhtml'>
  <head>
    <meta content='text/html;charset=UTF-8' http-equiv='content-type' />
  </head>
  <body>
    <script type='text/javascript'>
      //<![CDATA[
        something goes here.
        jQuery(function(){
          tog("#forgot_password_clicker", "#login_form");
          tog("#forgot_password_clicker", "#forgot_form", forgot_text);
        });
      //]]>
    </script>
  </body>
</html>

{ 1 trackback }

HAML and Javascript | Chris J Mears
October 20, 2009 at 11:00 pm

{ 0 comments… add one now }

Leave a Comment