Skip to content

Tagged Templates

Introduction

Previously, we discussed template strings, which conveniently allow variable interpolation to construct final strings:

javascript
let name = 'ming';
let age = 20;
let s = `Hello, ${name}, you are ${age} years old!`;
console.log(s);

In addition to this ease of use, template strings have a more powerful feature: tagged functions.

What is a Tagged Function?

Let's see an example:

javascript
const email = "test@example.com";
const password = 'hello123';

function sql(strings, ...exps) {
    console.log(`SQL: ${strings.join('?')}`);
    console.log(`SQL parameters: ${JSON.stringify(exps)}`);
    return {
        name: 'ming',
        age: 20
    };
}

const result = sql`SELECT * FROM users WHERE email=${email} AND password=${password}`;
console.log(JSON.stringify(result));

In this example, we see a peculiar syntax:

javascript
sql`SELECT * FROM users WHERE email=${email} AND password=${password}`

This syntax indicates that sql is a tagged function, and it automatically converts to a call to sql().

Parameters Passed to the Tagged Function

The sql() function actually receives two parameters:

  1. The first parameter, strings, is an array of strings: ["SELECT * FROM users WHERE email=", " AND password=", ""], consisting of the parts of the string that are not interpolated.

  2. The second parameter, ...exps, is a rest parameter that receives an array of the actual values from the template string: ["test@example.com", "hello123"], which are the results of parsing ${email} and ${password}.

The tagged function sql() behaves like a regular function. Inside, we concatenate strings to create an SQL query string and utilize ...exps as parameters to implement a secure SQL query. Note that we aren't performing an actual database connection here, so we return a fixed object.

Example of a Modification Function

If we wanted to modify the database, we could define a tagged function like this:

javascript
function update(strings, ...exps) {
    let sql = strings.join('?');
    // Execute database update
    // TODO:
}

This allows us to call it with a tagged template string:

javascript
let id = 123;
let age = 21;
let score = 'A';

update`UPDATE users SET age=${age}, score=${score} WHERE id=${id}`;

Isn't that very concise?

Tagged Templates has loaded