Twig
使用 Lingo.dev CLI 对 Twig 模板进行 AI 翻译
什么是 Twig?
Twig 是一个灵活、高效且安全的 PHP 模板引擎。它在 Symfony 应用和其他 PHP 框架中被广泛使用,用于将展示逻辑与应用逻辑分离。Twig 采用简洁的语法,使模板易于阅读和编写。
什么是 Lingo.dev CLI?
Lingo.dev CLI 是一个免费的开源命令行工具,可通过 AI 翻译应用和内容。它旨在替代传统的翻译管理软件,并可集成到现有的开发流水线中。
如需了解更多,请参见 概述。
关于本指南
本指南介绍如何使用 Lingo.dev CLI 翻译 Twig 模板。
你将学到如何:
- 从零创建项目
- 配置翻译流水线
- 使用 AI 生成翻译
前置条件
要使用 Lingo.dev CLI,请确保已安装 Node.js v18 及以上版本:
❯ node -v
v22.17.0
步骤 1. 创建项目
在你的项目目录下,创建一个 i18n.json 文件:
{
"$schema": "https://lingo.dev/schema/i18n.json",
"version": "1.10",
"locale": {
"source": "en",
"targets": ["es"]
},
"buckets": {}
}
该文件定义了翻译流水线的行为,包括需要翻译的语言以及本地化内容在文件系统中的位置。
如需了解可用属性,请参见 i18n.json。
步骤 2. 配置源语言环境
源语言环境 是指你的内容最初编写时所用的语言和地区。要配置源语言环境,请在 i18n.json 文件中设置 locale.source 属性:
{
"$schema": "https://lingo.dev/schema/i18n.json",
"version": "1.10",
"locale": {
"source": "en",
"targets": ["es"]
},
"buckets": {}
}
源语言环境必须以 BCP 47 语言标签 的形式提供。
如需查看 Lingo.dev CLI 支持的全部语言环境代码,请参见 支持的语言环境代码。
第 3 步:配置目标语言环境
目标语言环境 指的是您希望将内容翻译成的语言和地区。要配置目标语言环境,请在 locale.targets 属性中设置 i18n.json 文件:
{
"$schema": "https://lingo.dev/schema/i18n.json",
"version": "1.10",
"locale": {
"source": "en",
"targets": ["es"]
},
"buckets": {}
}
第 4 步:创建源内容
如果尚未创建,请新建一个或多个包含待翻译内容的 Twig 模板文件。这些文件的路径中必须包含源语言环境(例如,作为目录名 en/,或作为文件名的一部分 template_en.html.twig)。
对于 Twig 模板,可翻译内容包括:
- 块级元素中的文本内容:
h1-h6、p、div、li、blockquote、article、section等。 - 行内元素中的文本内容:
a、strong、em、span、code等。 - 属性值,包括:
content属性(在meta标签上)alt和title属性(在img标签上)placeholder、title、aria-label属性(在input、textarea、button、a、abbr、link标签上)
Twig 语法的处理方式:
Twig 模板语法在翻译过程中会被完整保留:
- Twig 变量和表达式(
{{ user.name }}、{{ product.price|number_format }})在可翻译文本中保持不变 - Twig 控制结构(
{% if %}、{% for %}、{% set %})会被保留且不翻译 - Twig 注释(
{# internal note #})会被保留且不翻译 - Twig 过滤器(
{{ "now"|date('Y') }})在翻译后的模板中依然可用
内联 HTML 的处理方式:
当文本包含内联 HTML 元素(如 <strong>、<span>、<em>、<a> 等)时,整个文本块会作为一个完整单元进行翻译。这不仅有助于提升翻译质量,还能保持内联格式。
例如:
<p>Hello <strong>{{ user.name }}</strong>, welcome back!</p>
整个段落 "Hello <strong>{{ user.name }}</strong>, welcome back!" 会作为一个整体进行翻译,同时保留 <strong> 标签和 Twig 变量。这样可以确保 AI 翻译器拥有完整上下文,并且在翻译中保留内联格式和 Twig 语法。
自动 lang 属性:
lang 属性会自动更新为目标语言,应用于 <html> 元素:
<!-- Source (en/template.html.twig) -->
<html>
<head>
<title>Welcome</title>
</head>
<!-- Target (es/template.html.twig) -->
<html lang="es">
<head>
<title>Bienvenido</title>
</head>
不可翻译内容:
位于 <script> 和 <style> 标签内的内容不会被翻译。
步骤 5. 创建 bucket
-
在
i18n.json文件中,向buckets对象添加一个"twig"对象:{ "$schema": "https://lingo.dev/schema/i18n.json", "version": "1.10", "locale": { "source": "en", "targets": ["es"] }, "buckets": { "twig": {} } } -
在
"twig"对象中,定义一个或多个include模式的数组:{ "$schema": "https://lingo.dev/schema/i18n.json", "version": "1.10", "locale": { "source": "en", "targets": ["es"] }, "buckets": { "twig": { "include": ["./[locale]/*.twig"] } } }这些模式用于定义需要翻译的文件。
模式本身:
- 必须包含
[locale]作为已配置语言的占位符 - 可以指向文件路径(如
"[locale]/template.html.twig") - 可以使用星号作为通配符(如
"[locale]/*.twig")
不支持递归 glob 模式(如
**/*.twig)。 - 必须包含
步骤 6. 配置 LLM
Lingo.dev CLI 使用大型语言模型(LLM)通过 AI 翻译内容。要使用这些模型,需要从支持的服务商获取 API 密钥。
为快速开始,推荐使用 Lingo.dev Engine:
-
运行以下命令:
npx lingo.dev@latest login这将打开默认浏览器并提示你进行身份验证。
-
按照提示操作。
步骤 7. 生成翻译
在包含 i18n.json 文件的目录下,运行以下命令:
npx lingo.dev@latest run
该命令将执行以下操作:
- 读取
i18n.json文件。 - 查找需要翻译的文件。
- 提取文件中的可翻译内容。
- 使用已配置的 LLM 翻译提取的内容。
- 将翻译后的内容写回文件系统。
首次生成翻译时,会创建一个 i18n.lock 文件。该文件用于记录已翻译的内容,防止后续运行时重复翻译。
示例
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>© {{ "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