如何在Pug模板文件中使用i18n变量?

5

我刚接触Node.js,正在学习如何在我的Pug模板中使用i18n,但无法在任何地方找到答案。

文档中说:

在您的模板中(取决于您的模板引擎)

<%= __('Hello') %>

${__('Hello')}

到目前为止,我已经尝试了在我的pug模板中:

${__('Hello')}

__('Hello')

没有一种语法是有效的,正确的语法是什么?我知道它已经配置好了,因为当使用时

i18n.__('Hello')

把它存储在变量中并将其发送到我的模板中,这样就可以正常工作。
4个回答

6
答案在文档中已经正确给出,我只需要将其添加到我的配置中即可。
app.use(function(req, res, next) {
    // express helper for natively supported engines
    res.locals.__ = res.__ = function() {
        return i18n.__.apply(req, arguments);
    };

    next();
});

1
这里的 'arguments' 是什么? - bvamos

5
除了Sam的答案之外,还要记住你应该使用#{__('Hello')}模板语法来使用这个i18n帮助程序。

4

您只需要执行npm i new one并按照以下方式注册全局。然后您就可以使用__('Hello')了。

const i18n = require("i18n");

app.use(i18n.init);
i18n.configure({
    locales: ['en', 'de', 'vi'],
    directory: './locales',
    register: global
});
i18n.setLocale('vi');

祝你好运!


0
不确定这是否有用。只是想分享一下。我遇到了同样的问题,在使用req.i18n.__()时可以看到翻译后的文本,但在pug中使用i18n-2却无法看到。我是如何解决的: 1. 确保i18n配置在app.use(cookieParser())之后。
// add i18n config after app used the cookieParser
var i18n = require('i18n-2');

// Attach the i18n property to the express request object
// And attach helper methods for use in templates
i18n.expressBind(app, {
    // setup some locales - other locales default to en silently
    locales: ['en', 'zh'],
    defaultLocale: 'en',
    // change the cookie name from 'lang' to 'locale'
    cookieName: 'locale'
});

app.use(function(req, res, next) {
  req.i18n.setLocaleFromQuery();
  req.i18n.setLocaleFromCookie();
  next();
});
  1. 请确保将以下模板设置放置在上述 i18n 配置之后。

    app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug');

  2. 在 pug 中,使用如下语法:#{__('Login')}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接