Reputation: 1812
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.
Upvotes: 6
Views: 10970
Reputation: 35
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!
Upvotes: 5
Reputation: 1
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();
});
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');
In pug, use syntax like: #{__('Login')}
Upvotes: 0
Reputation: 529
In addition to Sam's answer, bear in mind you should use #{__('Hello')}
template syntax to use this i18n helper.
Upvotes: 5
Reputation: 1812
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();
});
Upvotes: 7