Boban Jovanoski

Generating SHTML with middleman BobiYo Mar 11

6 comments Latest by remomos

Tags: shtml   frontend   middleman   haml  


Because I wanted to improve my css skills, I've decided to spend time learning css, optimizations, the whole front-end development shebang. The latest project I worked on, the client required static web site done using SSI/Server Side Includes.

SSI/Server Side Includes ???

I knew it was something old, but I never touhght 15 years back :) as Rolad pointed that out. It is same as html but you can include content from other files (think of it as using partials in html). You can also use "bash scripting" syntax in your html, I have not look deeply into it, all I needed was to use shtml just for including content.

How to turn on SSI? Simply open your apache conf file and add +Includes in your apache options and add shtml to the known file types.

Options  +Includes
AddType text/html .shtml
AddOutputFilter INCLUDES .shtml

How to include content using shtml? It is very simple, the syntax that the includes module will recognize is almost the same as writing comments in html. Example: (notice there is no empty space before the #):

<!--#include file="includes/header.shtml" -->

It's middleman time

After creating your middleman project (how to create new project and how to use middleman, you can check on the middleman wiki), you need to setup middleman to generate shtml files.

Middleman already does this for you, so you'll just need to name your files ending with ".shtml.haml".

The next thing that you'll need to do is to make middleman insert the required shtml syntax to include content from other files (I've used this for header.shtml and footer.shtml which were put inside the includes directory). To do this, I've defined an alias for the partial method inside middlemans config.rb file.

alias_method :shtml_partial, :partial

When the content is build I've defined the shtml_partial method like this:

def shtml_partial(*args)
   "<!--#include file=\"includes/#{args.first}.shtml\" -->"

Wherever the shtml_partial method is used (same as partial) instead of rendering the partials content, it will generate the required shtml include content from file. But the files inside the includes directory don't exist yet?!! For solving this, on build time, I've just copied the partials files that are used inside the includes directory.

File.copy_stream("views/_header.haml", 'views/includes/header.shtml.haml');
File.copy_stream("views/_footer.haml", 'views/includes/footer.shtml.haml');

Hint - Remember to use relative links when building :)

activate :relative_assets

Happy using Server Side Includes in 2011 :)

Feel free to comment about new sugestions. Thank you in advance.