Twig

AI translation for Twig templates with Lingo.dev CLI

What is Twig?

Twig is a flexible, fast, and secure template engine for PHP. It's widely used in Symfony applications and other PHP frameworks to separate presentation logic from application logic. Twig uses a clean syntax that makes templates easy to read and write.

What is Lingo.dev CLI?

Lingo.dev CLI is a free, open-source CLI for translating apps and content with AI. It's designed to replace traditional translation management software while integrating with existing pipelines.

To learn more, see Overview.

About this guide

This guide explains how to translate Twig templates with Lingo.dev CLI.

You'll learn how to:

  • Create a project from scratch
  • Configure a translation pipeline
  • Generate translations with AI

Prerequisites

To use Lingo.dev CLI, ensure that Node.js v18+ is installed:

❯ node -v
v22.17.0

Step 1. Set up a project

In your project's directory, create an i18n.json file:

{
  "$schema": "https://lingo.dev/schema/i18n.json",
  "version": "1.10",
  "locale": {
    "source": "en",
    "targets": ["es"]
  },
  "buckets": {}
}

This file defines the behavior of the translation pipeline, including what languages to translate between and where the localizable content exists on the file system.

To learn more about the available properties, see i18n.json.

Step 2. Configure the source locale

The source locale is the original language and region that your content was written in. To configure the source locale, set the locale.source property in the i18n.json file:

{
  "$schema": "https://lingo.dev/schema/i18n.json",
  "version": "1.10",
  "locale": {
    "source": "en",
    "targets": ["es"]
  },
  "buckets": {}
}

The source locale must be provided as a BCP 47 language tag.

For the complete list of the locale codes that Lingo.dev CLI supports, see Supported locale codes.

Step 3. Configure the target locales

The target locales are the languages and regions you want to translate your content into. To configure the target locales, set the locale.targets property in the i18n.json file:

{
  "$schema": "https://lingo.dev/schema/i18n.json",
  "version": "1.10",
  "locale": {
    "source": "en",
    "targets": ["es"]
  },
  "buckets": {}
}

Step 4. Create the source content

If you haven't already, create one or more Twig template files that contain the content to be translated. These files must be located at a path that includes the source locale somewhere in the path (e.g., as a directory name like en/ or as part of the filename like template_en.html.twig).

For Twig templates, translatable content includes:

  • Text content within block elements: h1-h6, p, div, li, blockquote, article, section, etc.
  • Text content within inline elements: a, strong, em, span, code, etc.
  • Attribute values including:
    • content attribute on meta tags
    • alt and title attributes on img tags
    • placeholder, title, and aria-label attributes on input, textarea, button, a, abbr, and link tags

How Twig syntax is handled:

Twig template syntax is fully preserved during translation:

  • Twig variables and expressions ({{ user.name }}, {{ product.price|number_format }}) are kept as-is within translatable text
  • Twig control structures ({% if %}, {% for %}, {% set %}) are preserved and not translated
  • Twig comments ({# internal note #}) are preserved and not translated
  • Twig filters ({{ "now"|date('Y') }}) remain functional in translated templates

How inline HTML is handled:

When text contains inline HTML elements (such as <strong>, <span>, <em>, <a>, etc.), the entire text block is translated as one complete unit. This preserves context for better translation quality and maintains inline formatting.

For example:

<p>Hello <strong>{{ user.name }}</strong>, welcome back!</p>

The entire paragraph "Hello <strong>{{ user.name }}</strong>, welcome back!" is translated as a single block, keeping both the <strong> tags and the Twig variable in place. This ensures the AI translator has full context and both inline formatting and Twig syntax are preserved in the translation.

Automatic lang attribute:

The lang attribute on the <html> element is automatically updated to match the target locale:

<!-- Source (en/template.html.twig) -->
<html>
<head>
    <title>Welcome</title>
</head>

<!-- Target (es/template.html.twig) -->
<html lang="es">
<head>
    <title>Bienvenido</title>
</head>

Non-translatable content:

Content within <script> and <style> tags is not translated.

Step 5. Create a bucket

  1. In the i18n.json file, add a "twig" object to the buckets object:

    {
      "$schema": "https://lingo.dev/schema/i18n.json",
      "version": "1.10",
      "locale": {
        "source": "en",
        "targets": ["es"]
      },
      "buckets": {
        "twig": {}
      }
    }
    
  2. In the "twig" object, define an array of one or more include patterns:

    {
      "$schema": "https://lingo.dev/schema/i18n.json",
      "version": "1.10",
      "locale": {
        "source": "en",
        "targets": ["es"]
      },
      "buckets": {
        "twig": {
          "include": ["./[locale]/*.twig"]
        }
      }
    }
    

    These patterns define which files to translate.

    The patterns themselves:

    • must contain [locale] as a placeholder for the configured locale
    • can point to file paths (e.g., "[locale]/template.html.twig")
    • can use asterisks as wildcard placeholders (e.g., "[locale]/*.twig")

    Recursive glob patterns (e.g., **/*.twig) are not supported.

Step 6. Configure an LLM

Lingo.dev CLI uses large language models (LLMs) to translate content with AI. To use one of these models, you need an API key from a supported provider.

To get up and running as quickly as possible, we recommend using Lingo.dev Engine:

  1. Sign up for a Lingo.dev account.

  2. Run the following command:

    npx lingo.dev@latest login
    

    This will open your default browser and ask you to authenticte.

  3. Follow the prompts.

Step 7. Generate the translations

In the directory that contains the i18n.json file, run the following command:

npx lingo.dev@latest run

This command:

  1. Reads the i18n.json file.
  2. Finds the files that need to be translated.
  3. Extracts the translatable content from the files.
  4. Uses the configured LLM to translate the extracted content.
  5. Writes the translated content back to the file system.

The first time translations are generated, an i18n.lock file is created. This file keeps track of what content has been translated, preventing unnecessary retranslations on subsequent runs.

Example

en/example.html.twig

{% set user = app.user %}
<!DOCTYPE html>
<html>
<head>
    <meta name="description" content="Welcome to our application">
    <title>Welcome</title>
</head>
<body>
    <header>
        <nav>
            <a href="/" title="Go to homepage">Home</a>
            <a href="/about" title="Learn more about us">About</a>
            <a href="/contact" title="Get in touch">Contact</a>
        </nav>
    </header>

    <main>
        <section class="hero">
            <h1>Welcome to Our Platform</h1>
            <p>Hello <strong>{{ user.name }}</strong>, we're glad to have you here!</p>
            <p>Start exploring our features and discover what makes us <em>unique</em>.</p>
        </section>

        {% if user.isPremium %}
        <section class="premium-benefits">
            <h2>Premium Benefits</h2>
            <ul>
                <li>Unlimited access to all features</li>
                <li>Priority customer support</li>
                <li>Advanced analytics and reporting</li>
            </ul>
        </section>
        {% endif %}

        <section class="getting-started">
            <h2>Getting Started</h2>
            <p>Follow these simple steps to begin your journey:</p>
            <ol>
                <li>Complete your profile</li>
                <li>Explore the dashboard</li>
                <li>Invite your team members</li>
            </ol>

            <form action="/profile/update" method="post">
                <label for="bio">Tell us about yourself:</label>
                <textarea id="bio" name="bio" placeholder="Enter your bio here" aria-label="User biography"></textarea>

                <label for="email">Email address:</label>
                <input type="email" id="email" name="email" placeholder="[email protected]" aria-label="Email address">

                <button type="submit" title="Save your profile changes">Save Profile</button>
            </form>
        </section>

        {# This section is for internal notes and won't be displayed #}
        {% if app.debug %}
        <section class="debug-info">
            <h3>Debug Information</h3>
            <p>User ID: {{ user.id }}</p>
            <p>Last login: {{ user.lastLogin|date('Y-m-d H:i:s') }}</p>
        </section>
        {% endif %}
    </main>

    <footer>
        <p>Need help? <a href="/support" title="Visit our support center">Contact Support</a></p>
        <p>&copy; {{ "now"|date('Y') }} Our Company. All rights reserved.</p>
    </footer>
</body>
</html>

es/example.html.twig

{% set user = app.user %}
<!DOCTYPE html>
<html lang="es">
<head>
    <meta name="description" content="Bienvenido a nuestra aplicación">
    <title>Bienvenido</title>
</head>
<body>
    <header>
        <nav><a href="/" title="Ir a la página de inicio">Inicio</a>
            <a href="/about" title="Conoce más sobre nosotros">Acerca de</a>
            <a href="/contact" title="Ponte en contacto">Contacto</a></nav>
    </header>

    <main>
        <section class="hero">
            <h1>Bienvenido a nuestra plataforma</h1>
            <p>Hola <strong>{{ user.name }}</strong>, nos alegra tenerte aquí!</p>
            <p>Comienza a explorar nuestras funciones y descubre lo que nos hace <em>únicos</em>.</p>
        </section>

        {% if user.isPremium %}
        <section class="premium-benefits">
            <h2>Beneficios premium</h2>
            <ul>
                <li>Acceso ilimitado a todas las funciones</li>
                <li>Soporte prioritario al cliente</li>
                <li>Análisis y reportes avanzados</li>
            </ul>
        </section>
        {% endif %}

        <section class="getting-started">
            <h2>Primeros pasos</h2>
            <p>Sigue estos sencillos pasos para comenzar tu experiencia:</p>
            <ol>
                <li>Completa tu perfil</li>
                <li>Explora el panel de control</li>
                <li>Invita a los miembros de tu equipo</li>
            </ol>

            <form action="/profile/update" method="post"><label for="bio">Cuéntanos sobre ti:</label>
                <textarea id="bio" name="bio" placeholder="Ingresa tu biografía aquí" aria-label="Biografía del usuario"></textarea>

                <label for="email">Dirección de correo electrónico:</label>
                <input type="email" id="email" name="email" placeholder="[email protected]" aria-label="Dirección de correo electrónico">

                <button type="submit" title="Guardar los cambios de tu perfil">Guardar perfil</button></form>
        </section>

        {# This section is for internal notes and won't be displayed #}
        {% if app.debug %}
        <section class="debug-info">
            <h3>Información de depuración</h3>
            <p>ID de usuario: {{ user.id }}</p>
            <p>Último inicio de sesión: {{ user.lastLogin|date('Y-m-d H:i:s') }}</p>
        </section>
        {% endif %}
    </main>

    <footer>
        <p>¿Necesitas ayuda? <a href="/support" title="Visita nuestro centro de soporte">Contacta con soporte</a></p>
        <p>© {{ "now"|date('Y') }} Nuestra empresa. Todos los derechos reservados.</p>
    </footer>
</body>
</html>

i18n.json

{
  "$schema": "https://lingo.dev/schema/i18n.json",
  "version": "1.10",
  "locale": {
    "source": "en",
    "targets": ["es"]
  },
  "buckets": {
    "twig": {
      "include": ["./[locale]/*.twig"]
    }
  }
}

i18n.lock

version: 1
checksums:
  2d3d028d905803e471ca9f97a4969d5e:
    head/0#content: 1308168cca4fa5d8d7a0cf24e55e93fc
    head/1: 3180ad6b8de344b781637750259e0f53
    body/0/0: 9de5fe40cbf5f851a6d2270f01fe0739
    body/1/0/0: c59070fe496d5e4bd0066295b63a9056
    body/1/0/1: 12d74865332bf1988d51e84ba67aae09
    body/1/0/2: 58f0e438e665c77eedc440c5a8529b1a
    body/1/1/0: 119e3aa396d12a5a1aa7058e0983f9b9
    body/1/1/1/0: 60f9a22f4200bb4620a6ff7a1797ec30
    body/1/1/1/1: 03846a81f16f5e4a11acfd9445ad497d
    body/1/1/1/2: 15aae9d70ff1fb682f7d86baca81dcc0
    body/1/2/0: fbd403146395526d68ac68d142a50e21
    body/1/2/1: da8dc7fe06175d8b805f7f565bfe2788
    body/1/2/2/0: 061e1acc1b9ebad9de09fd5626e813c7
    body/1/2/2/1: 67f022a3f9e278d065a063b5e29dd932
    body/1/2/2/2: 7e23f048179f6661050edaa796528fe0
    body/1/2/3: 635f7e9a4afc00de34f975914afbb8b8
    body/1/3/0: 7a7892379e31868abba9865d20be2b72
    body/1/3/1: 8740df822561d74d51bb30e4b39d6193
    body/1/3/2: 0429f12258fabbde3abaca3dd9986178
    body/2/0: d32e57e4a5a65f3bee8b63dcb2bfa8e7
    body/2/1: 7e10a8ab9cc4e6d603b3cdc48849688f