# gt-node: General Translation Node.js SDK: 文字列の翻訳
URL: https://generaltranslation.com/ja/docs/node/guides/translating-strings.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: gt-node で、General Translation を使ってハンドラー内の文字列、登録済みメッセージ、動的コンテンツを翻訳する方法。

`gt-node` では、文字列を翻訳する方法が 3 つあります。どれを使うかは、その文字列がどこにあり、事前にわかっているかどうかによって決まります。

*注: これら 3 つはいずれも、リクエストのロケールを認識できるように [`withGT`](/docs/node/guides/detecting-locale) のスコープ内で実行されます。*

## `getGT` を使って ハンドラー 内の文字列を翻訳する [#get-gt]

ハンドラー に直接記述した文字列を翻訳するには、[`getGT`](/docs/node/reference/functions/get-gt) を await して翻訳関数を取得し、それを呼び出します。値は ICU プレースホルダーで補間します。

```ts
import { getGT } from 'gt-node';

app.get('/api/greeting', async (req, res) => {
  const gt = await getGT();
  res.json({
    message: gt('Hello, world!'),
    welcome: gt('Welcome, {name}!', { name: 'Alice' }),
  });
});
```

これは、単発の文字列に対するデフォルトの選択肢です。用語の曖昧さを避けるには、`$context` を追加します。

## `msg` で登録済みメッセージを再利用する [#msg]

ハンドラー の外で定義する文字列 — 共有定数、エラーメッセージ、列挙型など — は、モジュールスコープで [`msg`](/docs/node/reference/functions/msg) を使って登録し、[`getMessages`](/docs/node/reference/functions/get-messages) で取得します。

```ts
import { msg, getMessages } from 'gt-node';

const NOT_FOUND = msg('Resource not found.');

app.use(async (req, res) => {
  const m = await getMessages();
  res.status(404).json({ error: m(NOT_FOUND) });
});
```

## `tx` を使って動的コンテンツを翻訳する [#tx]

事前に内容がわからず、事前生成もされていないコンテンツには、[`tx`](/docs/node/reference/functions/tx) を使ってランタイムで翻訳します。キャッシュミス時にはネットワークリクエストが発生するため、真に動的な文字列にのみ使用してください。

```ts
import { tx } from 'gt-node';

const translated = await tx(`Status: ${status}`);
```

*注: [`tx`](/docs/node/reference/functions/tx) は ICU プレースホルダーを使用しません。呼び出す前に、template literal を使って値を埋め込んでください。*

## アプローチを選ぶ [#choose]

* 単発のハンドラー内文字列 → [`getGT`](/docs/node/reference/functions/get-gt)。
* 共有定数やエラー → [`msg`](/docs/node/reference/functions/msg) と [`getMessages`](/docs/node/reference/functions/get-messages)。
* 動的で予測しにくいコンテンツ → [`tx`](/docs/node/reference/functions/tx)。
* キーで一元管理する文言 → [`getTranslations`](/docs/node/reference/functions/get-translations) を使った辞書。

## Next steps

- /docs/node/guides/detecting-locale
- /docs/node/guides/storing-translations
- /docs/node/guides/configuring

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
