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
%html
%head
%title Time
%body
= Time.now
Will generate
<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
%html
%head
%title Time and Footer
%body
= Time.now
= `haml footer.haml`
and we have a file named footer.haml
this is the footer
The HTML output will be
<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!