最佳實踐

將 URL 放入變數

在翻譯包含 URL 或類似資料的字串時,將這些 URL 放入變數中,然後在模板中引用它們被視為一種良好的做法。

<Translate
	string={`Click <a href="{{url}}">here</a>`}
	variables={{url: 'https://tacotranslate.com'}}
/>

使用 ARIA 標籤

在翻譯互動元素如按鈕的文字時,包含 ARIA 標籤以確保可及性是非常重要的。ARIA 標籤可以幫助螢幕閱讀器提供關於該元素功能的描述性資訊。

例如,如果你有一個按鈕讓使用者從程式碼區塊中複製文字,你可以使用 aria-label 屬性來提供清晰的描述:

<Translate
	aria-label={useTranslation('Copy to clipboard')}
	string="Copy"
/>

這種感覺有點非常元。

全域 origins 陣列與多重元件 origins

此模式僅適用於使用 Next.js Pages Router 時。

在處理較大型應用程式時,將字串和翻譯拆分成多個較小的來源是非常有益的。這種方法有助於減少打包大小和傳輸時間,確保本地化的效率和可擴展性。

當僅在客戶端渲染時,這種方式相當簡單;但在為伺服器端渲染取得翻譯時,來源管理會變得複雜。 不過,你可以透過使用 TacoTranslate 客戶端的 origins 陣列來自動化來源管理。

請參考此範例,我們已將元件和頁面分別置於不同的檔案中。

components/pricing-table.tsx
import TacoTranslate, {Translate} from 'tacotranslate/react';
import tacoTranslate from '../tacotranslate-client';

// Set an origin name for this component
const origin = 'components/pricing-table';

// Push the origin into the origins array as this file is imported
tacoTranslate.origins.push(origin);

export default function PricingTable() {
	return (
		<TacoTranslate origin={origin}>
			<Translate string="Pricing table" />
			// ...
		</TacoTranslate>
	);
}
pages/pricing.tsx
import TacoTranslate, {Translate} from 'tacotranslate/react';
import getTacoTranslateStaticProps from 'tacotranslate/next/get-static-props';
import tacoTranslateClient from '../tacotranslate-client';
import PricingTable from '../components/pricing-table';

const origin = 'pages/pricing';
tacoTranslateClient.origins.push(origin);

export default function PricingPage() {
	return (
		<TacoTranslate origin={origin}>
			<Translate string="Pricing page" />
			<PricingTable />
		</TacoTranslate>
	);
}

// We will now fetch translations for all imported components and their origins automatically
export async function getStaticProps(context) {
	return getTacoTranslateStaticProps(context, {client: tacoTranslateClient});
}

請參閱我們的 伺服器端渲染範例,了解有關 getTacoTranslateStaticProps 的更多資訊。

來自 Nattskiftet 的產品挪威製造