【问题标题】:i18n nodejs and frontend javascript localisationi18n nodejs 和前端 javascript 本地化
【发布时间】:2018-07-18 17:11:13
【问题描述】:

我正在使用 express js 4.0,并使用 ejs 视图配置了 https://github.com/mashpie/i18n-node i18n 模块。

我也希望支持 .js 文件。如何让 i18n 函数 __() 在 .js 文件中看到?

【问题讨论】:

    标签: javascript node.js express internationalization


    【解决方案1】:
    var i18n = require("i18n");
    var express = require('express')
    //I18n Module
    i18n.configure({
        locales: ['en'],
        defaultLocale: 'en',
        register: global,
        syncFiles: true,
        directory: __dirname + '/../locales'
    });
    i18n.setLocale('en');
    
    
    var router = express.Router()
    router.get('/i18n/:key', function (req, res, next) {
        var result = "Not Found";
        var key = req.params.key;
        if(key != null){
            result = i18n.__(key);
        }
    
        res.send(result);
    
    })
    
    router.get('/i18n.json', function (req, res, next) {
        res.send(i18n.getCatalog(i18n.getLocale()));
    });
    
    router.get("/i18n.js", function(req, res, next){
        var locals = i18n.getCatalog(i18n.getLocale());
        res.send("var __ = function(key) { var locals = "+JSON.stringify(locals)+"; return locals[key] != null ? locals[key] : key }");
    })
    
    
    
    
    
    module.exports = {
        config: function(req, res, next) {
    
            i18n.init(req, res);
    
            console.log("langueage inited")
            return next();
        },
        frontend: router
    }
    

    我制作了一个简单的工具,用于将语言环境作为 __() 暴露给前端。但是有现成的解决方案吗?

    要使用它,您只需添加 app.js

    var i18nConfig = require('./app/i18n')
    app.use(i18nConfig.config);
    app.use(i18nConfig.frontend);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多