I create mousemade pixel perfection stuffs for the interwebs.

Published: 3 years ago

Using HAML views in laravel

Haml (HTML abstraction markup language) makes HTML  look beautiful. Let me stop right there and point out that there is a better option, SLIM. However, it is only available for ruby. This specific project had to be done on PHP, therefore MtHAML (PHP implementation of HAML) turned out to be the best option available. Laravel is my framework of choice when I have to work with PHP, and this is how we can use HAML templates into Laravel. Laravel 4 TwigBridge With MtHaml does all the heavy lifting for us.

1. Install required packages:

For some reason, composer could not find mthaml/mthaml package. I added it before twigbridge, and everything worked well. Add these lines to require section of composer.json.

"mthaml/mthaml": "dev-master",
"zacoza/laravel-twigbridge": "dev-master"

After updating composer, add the ServiceProvider to the providers array in app/config/app.php


2. View extension:

Now you have support for TWIG and HAML template engines. You need to have .twig extension to your templates. To use HAML, put this line at the beginning of the view file:

{% haml %}

However, using .twig extension for HAML templates is not so good if you are using IDEs with code completion. Therefore I put _haml.twig extension for my view files, and configured *_haml.twig extension to be handled as HAML files in my PHPStorm IDE (Preferences -> IDE Settings -> File Types -> Select ‘HAML files’, add *_haml.twig under registered patterns).

3. Template Inheritance:

With template inheritance, you can create layout files and extend them, just like default blade engine of Laravel. First, define a block in your app/views/layout.haml.twig file,

    - block myBlockName
      %p Default content of block

Then in your app/views/custom.haml.twig file,

- extends 'layout_haml'
- block myBlockName
  %p Overridden content

4. Referencing view files:

Remember to use viewname_haml format while referencing any haml view, because we are using _haml.twig instead of .twig.

return View::make('home_haml');

Have fun!

Leave a Reply

Some HTML is OK