node.js 多语言快递应用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10866778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:49:17  来源:igfitidea点击:

Multilanguage express app

node.jsexpresspug

提问by buschtoens

I wonder what would be the best way to implement multiple versions / languages of the same content in the same layout in express.

我想知道在 express 中以相同的布局实现相同内容的多个版本/语言的最佳方法是什么。

Should I just do this?

我应该这样做吗?

app.get("/", function(req, res) {
    res.render(language + "/index");
});

Or is there a smarter / better way?

或者有更聪明/更好的方法吗?

回答by ziad-saab

I would suggest to keep only one template, as if you use one template per language it will get out of hand very quickly, let alone duplicate much content (and the small amount of "logic" you would put in a template too). Many applications use a tool called gettext to do the internationalization thing. There is a node.js library for it at https://github.com/DanielBaulig/node-gettext

我建议只保留一个模板,就好像您对每种语言使用一个模板一样,它会很快失控,更不用说复制大量内容(以及您将放入模板中的少量“逻辑”)。许多应用程序使用名为 gettext 的工具来进行国际化。在https://github.com/DanielBaulig/node-gettext有一个 node.js 库

Alternatively there is also i18n-node. It appears to have a bit more integration with express js.

或者,还有i18n-node。它似乎与 express js 有更多的集成。

回答by ankitjaininfo

The i18n-nodeis the simplest and greatest module that you should use. You can use directly in Javascript code or with Jade/Handlebar templates with express js.

国际化节点是,你应该使用最简单和最伟大的模块。您可以直接在 Javascript 代码中使用,也可以使用带有 express js 的 Jade/Handlebar 模板。

Why should you use i18n?

为什么要使用 i18n?

  • Auto detection of locale from the browser by header, cookie or query parameter depending on your setup.
  • It comes with examples as well.
  • It automatically generates a en.jsonby default inside ./locales/. This acts as a master file for you to start building new translations.
  • Supports Singular and plural forms
  • Support for parameters: __('Hello %s', 'Marcus')returns Hallo Marcus
  • 根据您的设置,通过标头、cookie 或查询参数从浏览器自动检测区域设置。
  • 它还带有示例。
  • 它会自动生成一个en.json默认内./locales/。这充当您开始构建新翻译的主文件。
  • 支持单复数形式
  • 支持参数:__('Hello %s', 'Marcus')返回Hallo Marcus

回答by Osman Erdi

i thought that we can define json objects in lang folder like , en.js , fr.js and this json files contains key value pairs than render to template according to user's language setting , lang settings can be into database.

我认为我们可以在 lang 文件夹中定义 json 对象,如 , en.js , fr.js 并且这个 json 文件包含键值对,而不是根据用户的语言设置渲染到模板,lang设置可以进入数据库。

And we can save this fr.js or anything else into res.locals for calling every template .

我们可以将此 fr.js 或其他任何内容保存到 res.locals 中以调用每个模板。

Is this suitable?

这个合适吗?