nuxt-i18nでHTMLタグを含む翻訳メッセージを表示する

作成日

2022年3月13日

nuxt-i18n を利用すれば多言語対応サイトを作ることができます.メッセージは単語や文章単位で翻訳して表示することができますが,場合によっては a タグなどの HTML タグを含む文章を使いたいかもしれません.

そのような場合には一部の単語を変数として埋め込むことで対応できます.

nuxt-i18nの設定

nuxt-i18n.config.js
export default {
  locales: [
    { code: 'en', iso: 'en-US', file: 'en.json' },
    { code: 'ja', iso: 'ja-JP', file: 'ja.json' },
  ],
  defaultLocale: 'en',
  langDir: 'locales/',
}

locales ディレクトリ以下に翻訳用ファイルを用意します.

nuxt.config.js
import i18n from './nuxt-i18n.config'

export default {
    ...,

  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
    ['@nuxtjs/i18n', i18n]
  ],
}

メッセージの準備

locales/en.json
{
    "message": "You agree to our {0}.",
    "tos": "Terms of Service"
}
locales/ja.json
{
    "message": "{0} に同意します。",
    "tos": "利用規約"
}

Vueファイルの記述

sample.vue
<template>
    <i18n path="message" tag="p">
        <a href="/term">{{ $t('tos') }}</a>
    </i18n>
</template>

<i18n> タグ内に記述した部分が変数として埋め込まれます.

参考

mktia's note

Research & Engineering / Blockchain / Web Dev

© 2017-2025 mktia. All rights reserved.