Translating HTML and JavaScript using Weblate CDN

Starting with Weblate 4.2 it is possible to export localization to a CDN using JavaScript本地化CDN addon.


此功能在托管的Weblate上配置。它需要在安装时进行额外的配置,见 LOCALIZE_CDN_URLLOCALIZE_CDN_PATH

Upon installation into your component it will push committed translations (see 惰性提交) to the CDN and these can be used in your web pages to localize them.


First, you need to create a monolingual component which will hold your strings, see 添加翻译项目和组件 for generic instructions on that.

In case you have existing repository to start with (for example the one containing HTML files), create an empty JSON file in the repository for the source language (see 源语言), for example locales/en.json. The content should be {} to indicate an empty object. Once you have that, the repository can be imported into Weblate and you can start with an addon configuration.


In case you have existing translations, you can place them into the language JSON files and those will be used in Weblate.

For those who do not want to use existing repository (or do not have one), choose Start from scratch when creating component and choose JSON file as a file format (it is okay to choose any monolingual format at this point).

正在配置 Weblate 内容分发网络附加组件

The JavaScript本地化CDN addon provides few configuration options.


Translations translated above this threshold will be included in the CDN.


Configures which strings from the HTML documents are translatable, see Weblate 内容分发网络的字符串提取 and 使用 Weblate 内容分发网络对 HTML 进行本地化操作.


Name of cookie which contains user selected language. Used in the JavaScript snippet for 使用 Weblate 内容分发网络对 HTML 进行本地化操作.


List of files in the repository or URLs where Weblate will look for translatable strings and offer them for a translation, see Weblate 内容分发网络的字符串提取.

Weblate 内容分发网络的字符串提取

翻译字符串必须在 Weblate 中出现。可以手动管理,使用 API 来建立,或使用 Extract strings from HTML files 列出文件或 URL ,Weblate 会自动提取它们。文件必须出现在残酷中,或者包含远程 URL ,由 Weblate下载并规则地分析。

CSS selector 的默认配置提取 CSS class l10n 的元素,例如从后面的一段中提取两个字符串:

<section class="content">
    <div class="row">
        <div class="wrap">
            <h1 class="section-title min-m l10n">Maintenance in progress</h1>
            <div class="page-desc">
                <p class="l10n">We're sorry, but this site is currently down for maintenance.</p>

在不想修改现有代码的情况下,还可以使用 * 作为选择器处理所有元素。



使用 Weblate 内容分发网络对 HTML 进行本地化操作

为了将 HTML 文件本地化,需要加载 weblate.js 脚本:

<script src="" async></script>

加载时,会自动发现所有匹配的翻译元素(基于 CSS selector ),并用翻译替代其文本。

从配置的 cookie 检测到用户语言,并退回到在浏览器中配置的用户首选语言。

The Language cookie name can be useful for integration with other applications (for example choose django_language when using Django).


单独的翻译在内容分发网络下暴露为双语 JSON 文件。要获取一个,你可以使用以下代码:

  .then(response => response.json())
  .then(data => console.log(data));