3

是否可以将参数传递给 RequireJS i18n 翻译的字符串?例如,我想定义这样的东西:

// nls/strings.js
define({
  'record_created': 'A record for :name has been created.'
});

然后像这样将数据传递给它:

var string = i18n.record_created('Nikola Tesla');

我在文档中找不到任何说这是可能的,但我之前在其他 i18n 库中做过这种事情。

4

1 回答 1

2

关于此主题的其他一些链接:

您可能可以从您选择的模板语言中自己构建一些东西。例如:

<script>
    define("myProps", {
        "record_created": "A record for {{name}} has been created at {{date}}"
    });

    define("myI18N", ["handlebars"], function(Handlebars) {
        function format(template, context) {
            var compiled = Handlebars.compile(template);
            return compiled(context);
        }

        function Wrapper(props) {
            var ob = {};
            for (var i in props) {
                ob[i] = format.bind(null, props[i]);
            }
            return ob;
        }

        return Wrapper;
    });

    require(["myProps", "myI18N"], function(props, i18n) {
        var ob = i18n(props);
        console.log(ob.record_created({
            name: "Meli",
            date: new Date()
        }));
    });
</script>

印刷:

A record for Meli has been created at Mon Sep 23 2013 20:32:39 GMT+0100 (GMT Daylight Time)

设置:

<script>
    require = {
        paths: {
            "handlebars": "https://rawgithub.com/wycats/handlebars.js/v1.0.12/dist/handlebars"
        },
        shim: {
            'handlebars': {
                exports: 'Handlebars'
            }
        }
    };
</script>
<script src="http://requirejs.org/docs/release/2.1.8/comments/require.js"></script>
于 2013-09-23T19:38:00.107 回答