使用 Weblate CDN 翻譯 HTML 和 JavaScript

Starting with Weblate 4.2 it is possible to export localization to a CDN using JavaScript 在地化 CDN add-on.

備註

此功能在託管的Weblate上配置。它需要在安裝時進行額外的配置,見 LOCALIZE_CDN_URLLOCALIZE_CDN_PATH

在安裝到您的組件中式,它將提交的翻譯推送到 CND(請參見 簡易提交),而這些可以在您的 web 頁面上使用來將其本地化。

Creating component

首先您需要新建單語言組件,它將保持您的字串,其一般指示請參見 添加翻譯項目和組件

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 add-on configuration.

提示

在您已有翻譯的情況下,您可以將其放置在語言 JSON 文件中,而那些將在 Weblate 中使用。

對於那些不想要使用(或不具有)現有倉儲的人,當新建組件時選擇:guilabel:Start from scratch,並選擇`JSON file` 作為文件格式(這是選擇任何單語言格式都可以)。

Configuring Weblate CDN add-on

The JavaScript 在地化 CDN add-on provides few configuration options.

最低翻譯數

在這個閾值之上的翻譯將包含在 CDN 中。

CSS 選擇器

配置來之 HTML 文件的哪些字串是可翻譯的,請參見 String extraction for Weblate CDNHTML localization using Weblate CDN

語言 Cookie 名稱

包含使用者所選擇的語言的 cookie 的名稱。在JavaScript 代碼段中用於 HTML localization using Weblate CDN

從 HTML 檔案擷取字串

倉儲中文件的列表,或 Weblate 尋找可翻譯字串並提供它們用於翻譯的 URLs,請參見 String extraction for Weblate CDN

String extraction for Weblate CDN

翻譯字串必須在 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>
            </div>
        </div>
    </div>
</section>

在不想修改現有代碼的情況下,還可以使用 * 作為選擇器處理所有元素。

備註

Right now, only text of the elements is extracted. This add-on doesn’t support localization of element attributes or elements with children.

HTML localization using Weblate CDN

為了將 HTML 文件本地化,需要加載 weblate.js 腳本:

<script src="https://weblate-cdn.com/a5ba5dc29f39498aa734528a54b50d0a/weblate.js" async></script>

加載時,會自動發現所有匹配的翻譯元素(基於 CSS selector ),並用翻譯替換其文本。

從配置的 cookie 檢測到使用者語言,並退回到在瀏覽器中配置的使用者首選語言。

Language cookie name 可以用於與其它應用集成(例如當使用 Django 時選擇 django_language)。

JavaScript localization

單獨的翻譯在內容分發網絡下揭露為雙語 JSON 文件。要獲取一個,您可以使用以下代碼:

fetch(("https://weblate-cdn.com/a5ba5dc29f39498aa734528a54b50d0a/cs.json")
  .then(response => response.json())
  .then(data => console.log(data));

在這種情況下需要採用實際的本地化邏輯。