最佳實踐
將 URL 放入變數中
When translating strings that contain URLs or similar data, it is considered a good practice to place these URLs inside variables and then referencing them within your templates.
<Translate
string={`Click <a href="{{url}}">here</a>`}
variables={{url: 'https://tacotranslate.com'}}
/>
使用 ARIA 標籤
When translating the text of interactive elements like buttons, it’s important to include ARIA labels to ensure accessibility. ARIA labels help screen readers provide descriptive information about the element’s function.
For instance, if you have a button that lets users copy text from a code block, you can use the aria-label
attribute to provide a clear description:
<Translate
aria-label={useTranslation('Copy to clipboard')}
string="Copy"
/>
Something about this feels very meta.
全域來源陣列與多重元件來源
This pattern only works when using the Next.js Pages Router.
當處理較大型應用程式時,將字串和翻譯拆分成多個較小的來源是有益的。這種方法有助於減少封包大小和傳輸時間,確保本地化的效率和可擴展性。
雖然在僅於客戶端渲染時這很簡單,但當為伺服器端渲染抓取翻譯時,管理來源很快會變得複雜。不過,你可以利用全域 origins
陣列自動化來源管理。
請參考此範例,我們已將元件和頁面拆分到不同的檔案中。
export const defaultOrigin = process.env.TACOTRANSLATE_ORIGIN;
const origins = [];
export default origins;
import TacoTranslate, {Translate} from 'tacotranslate/react';
import origins from '../utilities/tacotranslate-origins';
// Set an origin name for this component
const origin = 'components/pricing-table';
// Push the origin into the origins array as this file is imported
origins.push(origin);
export default function PricingTable() {
return (
<TacoTranslate origin={origin}>
<Translate string="Pricing table" />
// ...
</TacoTranslate>
);
}
import TacoTranslate, {Translate} from 'tacotranslate/react';
import origins from '../utilities/tacotranslate-origins';
import PricingTable from '../components/pricing-table';
const origin = 'pages/pricing';
export default function PricingPage() {
return (
<TacoTranslate origin={origin}>
<Translate string="Pricing page" />
<PricingTable />
</TacoTranslate>
);
}
// We can now fetch translations for all imported components and their origins automatically
export async function getStaticProps(context) {
return customGetStaticProps(context, [...origins, origin]);
}
請參閱我們的伺服器端渲染範例,以獲取有關 customGetStaticProps
的更多資訊。