À la bonne Sainte-Force

Tools

Tags

Generating captions for images in HTML articles from a Markdown document

19 September 2011

Dear friend,

Yes, my brande new website is up and running for thy pleasure only ! Thanks to nanoc I was able to turn it to whatever I wanted pretty quickly, hence I chose Markdown as my language of choice for publishing things. nanoc takes my Markdown pages and turns them into full HTML pages, with the proper layout, header, footer, and the like. Besides easing the writing process compared to verbose-as-hell HTML or even to figure-semantics-and-styling-issues-out-yourself WYSIWIG, the Markdown syntax is simple enough to be bearable on any text editor.

Some beautiful automatic caption.
Some beautiful automatic caption.

However, I had an issue with images, which I wanted to be accompanied with captions and correctly encapsulated in figure tags in the final HTML. Nothing seemed to work with plain Markdown, so I wrote a quick and dirty fix using the jQuery Javascript library. The fix looks for each image that has been generated from a Markdown document, writes a caption according to its alt attribute below and finally wraps it into a figure tag. How to recognize an image generated from Markdown from another ? Dead simple : the whole HTML coming from the Markdown document is placed in a div with the class markdown.

Let's see how a valiant and modern knight would accomplish this. First, include the jQuery library and the Javascript file containing our little trick on every page :

<script type="text/javascript" src="/jquery.js"></script> 
<script type="text/javascript" src="/my_secret_script.js"></script>
Put it in your <head> !

Now, let's write the secret script :

$(document).ready(function() {
	// Every image referenced from a Markdown document
	$(".markdown img").each(function() {
		// Let's put a caption if there is one
		if($(this).attr("alt"))
			$(this).wrap('<figure class="image"></figure>')
				.after('<figcaption>'+$(this).attr("alt")+'</figcaption>');
		});
});
my_secret_script.js, a little file with a big heart

If you did correctly the magic spell, it works and you see unicorns with captions. If not, please work harder. This trick is however not very satisfying because it would be better to do it right after the Markdown parsing, and not at the very last moment. A cleaner solution (in Ruby, of course) will come, some day, I promise !

Looking forward to hearing from you,
Hubert Sainte-Force