Gábor Imre Gábor Imre - 4 months ago 50
Javascript Question

ES6 tagged templates practical usability

I understand the syntax of ES6 tagged templates. What I don't see is the practical usability. When is it better than passing an object parameter, like the settings in jQuery's AJAX?

$.ajax('url', { /*this guy here*/ })

Right now I only see the tricky syntax but I don't see why I would need/use it. I also found that the TypeScript team chose to implement it (in 1.5) before other important features. What is the concept behind tagged string templates?


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.query("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.