Usage
In TechUI, multi-language functionality is implemented through the i18n function injected via global services. You can easily retrieve and use it within the setup syntactic sugar of your components.
Basic Calls
Injecting the Function
First, destructure the i18n method from $global.
import { inject } from 'vue';
const { i18n } = inject('$global');Retrieving Static Text
Use a dot-separated (.) path string to access specific text within the language package.
Usage in Script:
const title = i18n('controlPanel.title');
// Output: "Control Panel" (In a Chinese environment)Usage in Template:
<template>
<TuiButton>
{{ i18n('universal.confirm') }}
</TuiButton>
<p class="tip">
{{ i18n('login.tips.register') }}
</p>
</template>Dynamic Interpolation
When the translation text contains dynamic variables, the i18n function supports passing a second argument object for replacement.
Definition Format
In language package files, variables are defined using the ${variableName} format:
// Example language package definition
{
"panicAlert": {
"device": {
"content": "This page is exclusive to ${deviceA}, current access device is ${deviceB}..."
}
}
}Call Example
When calling, pass an object containing the corresponding key-value pairs:
const alertMessage = i18n('panicAlert.device.content', {
deviceA: 'PC',
deviceB: 'Mobile'
});
// Output: "This page is exclusive to PC, current access device is Mobile..."Debugging Tools
During development, if you encounter translations that do not display or have difficulty finding Key values, you can use the debugging tool function tConsolei18n provided by TechUI.
This function is primarily used to output debugging information to the browser console, helping developers confirm:
- Whether the current Key exists.
- Whether the currently loaded language package data is correct.
- Whether interpolation parameters are correctly parsed.
import { inject } from 'vue';
const { tConsolei18n } = inject('$global');
// Print translation details for a specific Key in the console
tConsolei18n('navTab.menu.close');FAQ
Q: What is displayed if a Key does not exist?A: If the passed Key cannot be found in the current language package, the i18n function will return the Key string itself by default (e.g., returning "unknown.key.path"). This helps developers quickly identify missing translation items.
Q: Are HTML tags supported?A: The i18n function returns a plain string. If you need to include HTML in your translations (such as bold text or line breaks), use Vue's v-html directive. However, please ensure the security of the translation content to prevent XSS attacks.
<span v-html="i18n('some.rich.text')"></span>