SVG and Handlebars JS Templates

I’ve been working with Handlebars JS for a while and wanted to use templating to generate portions of SVG.  If you read my last post on SVG and JavaScript, a proper namespace is the key to the SVG castle.  So I needed a way to get the output from my Handlebars template to be seen as proper SVG.

This is the handlebars template I’m working with.

This template is for a single character from my Auto Andy project.

First thing to do is create a SVG Element.

I’m just going to put the template in a local variable for this demo.

Next step is create some data and run it through the Handlebars template.  This data below is just a single output from running Auto Andy.

When I compile the template with the data, I end up getting back a string that represents the final markup.  Now I need to turn that markup into SVG elements with the proper namespace.

The DOMParser found in the vanilla JavaScript looked to be the ticket.  The DOMParser has a parseFromString method to create JavaScript accessible XML objects.  The object returned has a property call documentElement that contains the root node of the document. The last step is appending the root node to the SVG element.

Everything looks to be in place, but if I run this code I end up with my old friend the “Empty Page”.  So why doesn’t it show up? O’Yeah, namespace! When I called parseFromString(), the XML string was parsed using the default XML namespace.  However, I can change that by altering the template a little.

Setting the XML Namespace to the SVG namespace seems to fix the problem.  Now when I run the markup through parseFromString() it parses the XML string using the SVG namespace.

View Demo on jsFiddle

Using jQuery?

If you are using jQuery with your project, you can use the $.parseXML() method instead of the direct use of DOMParser.parseFromString() to get the same result.