# gt-next: General Translation Next.js SDK: msg
URL: https://generaltranslation.com/zh/docs/next/api/strings/msg.mdx
---
title: msg
description: msg() 字符串函数的 API 参考文档
---
{/* 自动生成:请勿直接编辑。请改为编辑 content/docs-templates/ 中的模板。 */}
## 概述
`msg` 函数用于标记并编码要翻译的字符串。
```jsx
const encodedString = msg('Hello, world!');
```
编码后的字符串应传递给 [`useMessages`](/docs/next/api/strings/use-messages) Hook,以获取翻译结果。
**编码:**
`msg` 会对输入字符串进行编码,因此不能直接在 JSX 或其他地方使用。
如果你想取回原始字符串,需要使用 [`decodeMsg`](#decodemsg) 对其进行解码。
## 解码 [#decodemsg]
要恢复原始字符串,你需要使用 [`decodeMsg`](#decodemsg) 对其进行解码
```jsx
import { msg, decodeMsg } from 'gt-next';
const encodedString = msg('Hello, world!');
const decodedString = decodeMsg(encodedString);
console.log(decodedString); // "Hello, world!"
```
## 参考文档
### 参数
| 名称 | 类型 | 描述 |
| ---------- | ----------------------------------------------------------------------------- | ------------------ |
| `content` | `string` | 要进行编码的字符串内容。 |
| `options?` | [`InlineTranslationOptions`](/docs/next/api/types/inline-translation-options) | 用于自定义 `msg` 行为的选项。 |
### 返回值
一个已编码的字符串,其中插值变量 (如果有) 会被替换为对应的值。
***
## 行为
### 生产环境
在持续部署 (CD) 过程中,`msg` 函数中的任何内容都会在应用部署前完成翻译。
这可确保所有区域设置下都能快速加载,但它只能翻译在构建时已知的内容。
生成后,翻译内容会根据你的配置以以下两种方式之一存储: (1) 存储在 CDN 中,或 (2) 存储在应用的构建输出中。
随后,这些已翻译的内容会提供给用户。
如果找不到翻译,则会回退到原始内容。
请务必遵循[此处的部署指南](/docs/next/tutorials/quickdeploy)。
### 开发
在开发过程中,`msg` 函数会按需翻译内容。
这有助于你在原型设计阶段预览应用在不同语言下的显示效果。
请记得在环境变量中添加 Dev API 密钥,以启用此行为。
在开发环境中进行按需翻译时,你会感受到一定延迟。
除非内容被明确配置为按需翻译,否则生产构建中不会出现这种情况。
***
## 示例
### 基本用法
你可以使用 `msg` 将字符串标记为待翻译内容。
```jsx copy
import { msg, useMessages } from 'gt-next';
const encodedString = msg('Hello, world!');
export default function TranslateGreeting() {
const m = useMessages();
return (
{m(encodedString)}
);
}
```
注意:"Hello, world!" 会被翻译成用户的首选语言。
### 使用变量 [#variables]
你可以向字典中的翻译传入变量。
```jsx copy
import { msg, useMessages } from 'gt-next';
const encodedString = msg('Hello, {name}!', { name: 'Alice' });
export default function TranslateGreeting() {
const m = useMessages();
return (
{m(encodedString)}
);
}
```
注意:"Alice" 不会被翻译成用户的首选语言,因为它是一个变量。
### 使用 ICU 消息格式
`gt-next` 支持 ICU 消息格式,因此你也可以对变量进行格式化。
```jsx copy
import { msg, useMessages } from 'gt-next';
const encodedString = msg('There are {count, plural, =0 {no items} =1 {one item} other {{count} items}} in the cart', { count: 10 });
export default function TranslateGreeting() {
const m = useMessages();
return (
{m(encodedString)}
);
}
```
ICU 消息格式是一种功能强大的变量格式化方式。
更多信息,请参阅 [ICU 消息格式文档](https://unicode-org.github.io/icu/userguide/format_parse/messages/)。
***
## 说明
* `msg` 函数用于将字符串标记为待翻译内容。
* 使用 `msg` 的字符串会在 runtime 之前、也就是构建阶段完成翻译 (开发环境除外) 。
## 后续步骤
* 关于如何翻译字符串,请参阅 [`useMessages`](/docs/next/api/strings/use-messages)。