You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SailsJS中集成i18next并在Handlebars模板中使用

在SailsJS中集成i18next并在Handlebars模板中实现翻译

1. 安装必要依赖

首先安装核心包及配套插件:

npm install i18next i18next-http-middleware i18next-fs-backend

2. 配置i18next

在项目config目录下新建i18next.js文件,初始化i18next并配置翻译文件存储、语言检测规则:

const i18next = require('i18next');
const Backend = require('i18next-fs-backend');
const middleware = require('i18next-http-middleware');

i18next
  .use(Backend)
  .use(middleware.LanguageDetector)
  .init({
    fallbackLng: 'en', // 默认回退语言
    debug: false, // 生产环境建议关闭调试日志
    backend: {
      loadPath: './locales/{{lng}}/{{ns}}.json', // 翻译文件路径模板
    },
    detection: {
      order: ['cookie', 'header'], // 优先从Cookie取语言,其次是请求头
      caches: ['cookie'], // 将用户选择的语言缓存到Cookie
    },
    ns: ['translation'], // 默认命名空间
    defaultNS: 'translation',
  });

module.exports = { i18next, middleware };

3. 将i18next中间件注册到SailsJS

修改config/http.js,把i18next中间件加入Sails的中间件执行链:

const { middleware: i18nextMiddleware } = require('./i18next');

module.exports.http = {
  middleware: {
    order: [
      'cookieParser',
      'session',
      'i18next', // 放在session之后、router之前
      'bodyParser',
      'compress',
      'poweredBy',
      'router',
      'www',
      'favicon',
    ],

    // 定义i18next中间件
    i18next: i18nextMiddleware.handle(i18next),
  },
};

4. 给Handlebars添加翻译助手

修改config/views.js,注册一个名为t的Handlebars助手,用于模板内的翻译调用:

const { i18next } = require('./i18next');

module.exports.views = {
  engine: 'handlebars',
  layout: 'layouts/main',

  // 注册Handlebars翻译助手
  helpers: {
    t: function(key, options) {
      // 从请求对象获取当前语言,无则用默认语言
      const lng = this.req?.i18n?.language || i18next.options.fallbackLng;
      return i18next.t(key, { lng, ...options.hash });
    }
  }
};

5. 创建翻译文件

在项目根目录新建locales文件夹,按语言分类存放翻译JSON:

  • locales/en/translation.json
{
  "welcome": "Welcome to our application",
  "greeting": "Hello, {{name}}!"
}
  • locales/zh-CN/translation.json
{
  "welcome": "欢迎来到我们的应用",
  "greeting": "你好,{{name}}!"
}

6. 在控制器和模板中使用翻译

控制器内调用

// api/controllers/HomeController.js
module.exports = {
  index: async function(req, res) {
    // 通过req.t获取翻译文本
    const welcomeText = req.t('welcome');
    return res.view('home/index', { welcomeText });
  }
};

Handlebars模板内调用

<!-- views/home/index.handlebars -->
<h1>{{t 'welcome'}}</h1>
<p>{{t 'greeting' name='张三'}}</p>

注意事项

  • 语言切换:可通过设置lang Cookie或发送Accept-Language请求头切换语言
  • 生产环境:关闭i18next的debug模式,减少冗余日志
  • 多命名空间:翻译内容较多时,可拆分到不同命名空间,调用时指定ns参数

内容的提问来源于stack exchange,提问作者MAK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 20:32:23