How to use i18n variables in Pug template files?
Asked Answered
O

4

6

I'm new to Node.js and I'm trying to learn how to use i18n in my Pug template and could not find my answer anywhere.

The documentation says

in your templates (depending on your template engine)

<%= __('Hello') %>

${__('Hello')}

So far I tried (in my pug template)

${__('Hello')}

__('Hello')

None of those syntax is working, what is the correct one to use ?

I know it is well configure because when using

i18n.__('Hello')

And sending it to my template in a variable it is working.

Odessaodetta answered 3/2, 2017 at 9:26 Comment(0)
O
7

Answer was right in the documentation, only needed to add this to my configuration.

app.use(function(req, res, next) {
    // express helper for natively supported engines
    res.locals.__ = res.__ = function() {
        return i18n.__.apply(req, arguments);
    };

    next();
});
Odessaodetta answered 3/2, 2017 at 9:46 Comment(2)
What is 'arguments' here?Bargain
@Bargain arguments is the implicit list of parameters a function gets in JavaScript, see developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Cowslip
G
5

In addition to Sam's answer, bear in mind you should use #{__('Hello')} template syntax to use this i18n helper.

Grandpapa answered 18/1, 2018 at 4:58 Comment(0)
A
5

You just need to npm i new one and register global as below. Then you can use __('Hello').

const i18n = require("i18n");

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

Good luck!

Anniceannie answered 19/1, 2019 at 4:3 Comment(0)
C
0

Not sure whether this is useful. Just like to share. I encountered the same problem where i can see the translated text using req.i18n.__() but cannot see in the pug using i18n-2. How I solved is: 1. make sure the i18n config is after the 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. Make sure the following template setting is placed after the above i18n config.

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

  2. In pug, use syntax like: #{__('Login')}

Corned answered 22/3, 2018 at 9:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.