# python: t URL: https://generaltranslation.com/zh/docs/python/api/t.mdx --- title: t description: t 翻译函数的 API 参考文档 --- ## 概述 `t` 函数用于翻译并插值 ICU MessageFormat 字符串中的变量。 它会查找当前区域设置,根据哈希找到缓存的译文,并插值变量。 如果找不到译文,则回退到源字符串。 ```python from gt_flask import t # 或从 gt_fastapi import t message = t("Hello, {name}!", name="World") ``` ## 参考 ### 参数 ### GT 选项 (通过 `**kwargs` 传递) | 选项 | 类型 | 说明 | | ------------ | ----- | ------------------- | | `_context` | `str` | 附加上下文,用于区分源文本相同的翻译。 | | `_id` | `str` | 翻译条目的自定义标识符。 | | `_max_chars` | `int` | 输出的最大字符长度。 | ### 返回值 `str` — 翻译并插值后的字符串。 *** ## 示例 ### 简单翻译 ```python t("Hello, world!") ``` ### 使用变量 ```python t("Hello, {name}!", name="Alice") ``` ### 使用 context ```python t("Bank", _context="financial institution") t("Bank", _context="river bank") ``` ### 配合 f-string 和 `declare_var` Python 的 f-string 可与 `t` 自然搭配使用——只需用 [`declare_var`](/docs/python/api/declare-var) 包裹变量: ```python from gt_flask import t, declare_var # i18n 之前: message = f"{name} goes home" # i18n 之后——只需用 t() 和 declare_var() 包裹: message = t(f"{declare_var(name, name='name')} goes home") ``` ### 带有字符限制 ```python t("This is a very long message that might need truncation", _max_chars=20) ``` *** ## 注意事项 * 必须先调用 [`initialize_gt`](/docs/python/api/initialize-gt),才能使用 `t`。 * 如果当前区域设置与默认区域设置一致,则不会执行翻译查找,只会进行插值。 * 变量会使用 ICU MessageFormat 语法进行插值 (例如:`{name}`、`{count, plural, one {# item} other {# items}}`) 。