ES6 tagged templates practical usability

You can use tagged templates to build APIs that are more expressive than regular function calls.

For example, I’m working on a proof-of-concept library for SQL queries on JS arrays:

let admins = sql`SELECT name, id FROM ${users} 
                 WHERE ${user => user.roles.indexOf('admin') >= 0}`

Notice it has nothing to do with String interpolation; it uses tagged templates for readability. It would be hard to construct something that reads as intuitively with plain function calls – I guess you’d have something like this:

let admins = sql("SELECT name, id FROM $users WHERE $filter",
  { $users: users, $filter: (user) => user.roles.contains('admin') })

This example is just a fun side project, but I think it shows some of the benefits of tagged templates.

Another example, maybe more obvious, is i18n – a tagged template could insert locale-sensitive versions of your input.

Leave a Comment