Home >Web Front-end >JS Tutorial >TIL: Tag Function / Tagged Template Literals

TIL: Tag Function / Tagged Template Literals

Barbara Streisand
Barbara StreisandOriginal
2025-01-09 08:34:40972browse

TIL: Tag Function / Tagged Template Literals

Overview ?

Tagged Functions, also known as Tagged Template Literals, are an advanced feature of template literals introduced in ES6 (2015). They enable more control over how template literals are processed, allowing for custom formatting, parsing, or even validation.

One popular use case for tagged template literals is in GraphQL for building query strings dynamically.


Syntax

Definition

A tagged template literal is a combination of a "tag function" and a template literal. The tag function receives the literal's strings and interpolated values as arguments, enabling custom processing.

Here’s a basic example:

const bar = "var bar";

function tag(strings, ...values) {
  console.log(strings); // Array of string literals
  console.log(values);  // Array of interpolated values
}

Usage

tag`foo ${bar} baz`;

// Output:
// ['foo ', ' baz']  // Array of strings
// ['var bar']       // Array of values

Use Cases

1. Internationalization (i18n)

Tagged template literals can be used to process strings dynamically for localization.

Example:

function i18n(strings, ...values) {
  const translations = {
    "Hello, ": "Hola, "
  };

  return strings.reduce((acc, str, i) => {
    const translatedStr = translations[str] || str; // Translate if possible
    return acc + translatedStr + (values[i] || '');
  }, '');
}

const name = "Alice";
const result = i18n`Hello, ${name}!`;
console.log(result);
// Output: "Hola, Alice!"

2. GraphQL

In GraphQL, tagged template literals are widely used to define and manipulate query strings.

Example:

const query = gql`
  query {
    user(id: 1) {
      name
      age
    }
  }
`;

3. Handling Arguments with Tagged Template Literals

Tagged template literals can also process arguments by passing an additional value to the tag function and applying functions within the template literal.

Example:

function tagged(baseValue) {
  return function(strings, ...functions) {
    return strings.reduce((acc, str, i) => {
      const value = typeof functions[i] === 'function' ? functions[i](baseValue) : '';
      return acc + str + value;
    }, '');
  };
}

const result = tagged(2)`foo${n => n * 0}bar${n => n * 1}baz${n => n * 2}`;
console.log(result);
// Output:
// "foo0bar2baz4"


Discussion and Insights ?

Tagged template literals enable dynamic string processing with custom logic, making them ideal for use cases like query building, internationalization, and input sanitization. They improve code readability and maintainability, especially in scenarios requiring advanced string manipulation.


References

  • MDN Web Docs: Tagged Templates
  • ES6 Specification
  • GraphQL Official Documentation
  • Tagged Template Literals の TypeScript推論

The above is the detailed content of TIL: Tag Function / Tagged Template Literals. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn