Javascript Templating

Text templating/substitution (also known as string interpolation) is really nice to have. I’ve found this very useful in Javascript when building simple browser apps that call a SPARQL server. In fact I recently wrote this up as a paper, with a couple of little demos, proposing a pattern I call Sparql Diamonds. However, I missed a trick.

I used the Hogan lib, developed at Twitter. This, like several other libs, implements the Mustache “logic-less” templating spec. Chatting with Bergi the other day he happened to mention that ECMAScript supports a kind of templating natively, known as Template Literals. That’s ECMAScript 2015 (+), so it’s been around for a while and is supported by modern browsers. D’oh!

(They also provide multi-line string literals, which is also kinda handy).

There are plenty of blog posts & tutorials around describing template literals.

I think I did use a couple of extra features of Hogan/Mustache that aren’t in ECMAScript, but wouldn’t really have been necessary. The key part I was using can look like this :

var wikidatanameQT = function (name) {
return `
         PREFIX schema: <http://schema.org/> 
         
         SELECT DISTINCT ?link WHERE { 
              ?link schema:name "${name}"@en . 
         }
       `
}

(note the backticks)

– then calling eg. wikidatanameQT(“Fish”) will yield the query with the ${name} part replaced with Fish.

It’s trivial to add extra variables to such a function, or pass it an object, say user with properties like user.name that can be used in the template. Similarly in my Diamonds thing I had HTML being templated, eg.

var linkHT = function (link) { 
    return `<li><a href='${link}'>${link}</a></li>`
}

(It’ll no doubt be a while before I get around to updating the paper & demos…)

admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment