使用 TacoTranslate
翻譯字串
目前有三種方式可以翻譯字串:Translate
元件、useTranslation
hook,或是 translateEntries
工具。
使用 Translate
元件。
輸出在 span
元素內的翻譯,並支援呈現 HTML。
import {Translate} from 'tacotranslate/react';
function Page() {
return <Translate string="Hello, world!" />;
}
您可以使用例如 as="p"
在組件上更改元素類型。
使用 useTranslation
鉤子。
回傳純文字的翻譯。適用於例如 meta
標籤中。
import {useEffect} from 'react';
import {useTranslation} from 'tacotranslate/react';
function Page() {
const helloWorld = useTranslation('Hello, world!');
useEffect(() => {
alert(helloWorld);
}, [helloWorld]);
return (
<title>{useTranslation('My page title')}</title>
);
}
使用 translateEntries
工具。
在伺服器端翻譯字串。為你的 OpenGraph 圖片增強功能。
import {createEntry, translateEntries} from 'tacotranslate';
async function generateMetadata(locale = 'es') {
const title = createEntry({string: 'Hello, world!'});
const description = createEntry({string: 'TacoTranslate on the server'});
const translations = await translateEntries(
tacoTranslate,
{origin: 'opengraph', locale},
[title, description]
);
return {
title: translations(title),
description: translations(description)
};
}
字串如何被翻譯
當字串到達我們的伺服器時,我們會先驗證並保存它們,然後立即返回機器翻譯。雖然機器翻譯的品質通常低於我們的 AI 翻譯,但它們能提供快速的初步回應。
同時,我們會啟動非同步翻譯工作,為您的字串產生高品質、最先進的 AI 翻譯。一旦 AI 翻譯準備好,將會取代機器翻譯,並在您每次請求字串翻譯時提供。
如果您已手動翻譯了某個字串,則會優先使用並回傳這些翻譯。
利用來源
TacoTranslate 專案包含我們所稱的 origins。可以將它們視為字串和翻譯的入口點、資料夾或群組。
import {TacoTranslate} from 'tacotranslate/react';
function Menu() {
return (
<TacoTranslate origin="application-menu">
// ...
</TacoTranslate>
);
}
起源讓您將字串分隔到具意義的容器中。 例如,您可以為文件設定一個起源,為您的行銷頁面設定另一個起源。
要獲得更細緻的控制,您可以在元件層級設定 origins。
要實現此目的,請考慮在您的專案中使用多個 TacoTranslate 提供者。
請注意,相同的字串在不同的 origins 可能會有不同的翻譯。
最終,如何將字串分隔到不同的 origins 全憑您和您的需求決定。但請注意,在同一個 origin 中包含大量字串可能會增加載入時間。
import {Translate} from 'tacotranslate/react';
function Greeting() {
const name = 'Juan';
return <Translate string="Hello, {{name}}!" variables={{name}} />;
}
import {useTranslation} from 'tacotranslate/react';
function useGreeting() {
const name = 'Juan';
return useTranslation('Hello, {{name}}!', {variables: {name}});
}
管理 HTML 內容
預設情況下,Translate
元件支援並渲染 HTML 內容。然而,您可以透過將 useDangerouslySetInnerHTML
設為 false
來選擇退出此行為。
強烈建議在翻譯不受信任的內容(例如用戶生成的內容)時禁用 HTML 呈現。
所有輸出在呈現前都會使用 sanitize-html 進行清理。
import {Translate} from 'tacotranslate/react';
function Page() {
return (
<Translate
string={`
Welcome to <strong>my</strong> website.
I’m using <a href="{{url}}">TacoTranslate</a> to translate text.
`}
variables={{url: 'https://tacotranslate.com'}}
useDangerouslySetInnerHTML={false}
/>
);
}
上述範例將會以純文字格式呈現。