2015-02-18

For a recent project, I decided to use HAML for generating HTML. Having used HAML at work for quite some time, I find it to be a great way to maintain and work with HTML in a very readable fashion.

One concern I had with HAML was the lack of functionality for including a partial file. Fortunately, there is a very easy solution; using backticks in a Ruby interpreter.

In a HAML file "=" can be used to run Ruby code and the output of the code will be included in the compiled HTML output. For example, to include the current time in the HTML, one needs to add "= Time.now" to the HAML file.

Using this method, he following HAML code

!!! 5
%html
    %head
        %title Time
    %body
        = Time.now

Will generate

<!DOCTYPE html>
<html>
  <head>
    <title>Time</title>
  </head>
  <body>
    2015-02-18 10:41:28 -0800
  </body>
</html>

In Ruby, backticks "`" can be used to execute a shell command, and since the command for converting a haml file to html is "haml path_to_haml_file", one needs to add "= `haml path_to_partial_file`" in a template in order to render a partial file.

Thus, if we start with

!!! 5
%html
    %head
        %title Time and Footer
    %body
        = Time.now
        = `haml footer.haml`

and we have a file named footer.haml

#footer
    this is the footer

The HTML output will be

<!DOCTYPE html>
<html>
  <head>
    <title>Time</title>
  </head>
  <body>
    2015-02-18 11:07:44 -0800
    <div id='footer'>
      this is the footer
    </div>
  </body>
</html>

Well there you have it, a nice and simple way to render a partial file in a HAML template. Code on!

Comments
Name:
not required
Email:
not required (will not be displayed)
Website:
not required (will link your name to your site)
Comment:
required
Please do not post HTML code or bbcode unless you want it to show up as code in your post. (or if you are a blog spammer, in which case, you probably aren't reading this anyway).
Prove you are human by solving a math problem! I'm sorry, but due to an increase of blog spam, I've had to implement a CAPTCHA.
Problem:
0 plus 8
Answer:
required
  • Tags:
subscribe
 
2019
2016
2015
2014
2013
2012
2011
2010
December
November
October
September
August
July
June
May
April
March
February
January
2009
December
November
October
September
August
July
June
May
April
March
February
January
2008