如何在Meteor中翻译模板?

时间:2013-10-02 12:03:57

标签: meteor

已更新 现在我尝试在我的应用程序中执行此操作(thx to Akshat)

//共同

LANG = 'ru';
Dictionary = new Meteor.Collection("dictionary");

//if server
    Meteor.startup(function () {
    if (Dictionary.find().count() === 0) {
        // code to fill the Dictionary
    }
    });


    Meteor.publish('dictionary', function () {
        return Dictionary.find();
    });
//endif

//客户端

t = function(text) {
    if (typeof Dictionary === 'undefined') return text;
    var res = Dictionary.find({o:text}).fetch()[0];
    return res && res.t;
}

    Meteor.subscribe('dictionary', function(){ 
      document.title = t('Let the game starts!'); 
    });

    Template.help.text = t('How to play');

// HTML

<body>
  {{> help}}
</body>


<template name="help">
    {{text}}
</template>

仍然无法正常工作:模板渲染时未定义字典。但是控制台中的t('How to play')可以很好地工作)

1 个答案:

答案 0 :(得分:1)

客户端和服务器之间不会共享Javascript变量。您必须使用Meteor Collection来存储数据,例如

if (Meteor.isServer) {

    var Dictionary = new Meteor.Collection("dictionary");

    if(Dictionary.find().count() == 0) {
    //If the 'dictionary collection is empty (count ==0) then add stuff in

        _.each(Assets.getText(LANG+".txt").split(/\r?\n/), function (line) {
            // Skip comment lines
            if (line.indexOf("//") !== 0) {
                var split = line.split(/ = /);
                DICTIONARY.insert({o: split[0], t:split[1]});
            }
        });
    }

}

if (Meteor.isClient) {

    var Dictionary = new Meteor.Collection("dictionary");

    Template.help.text = function() {
        return Dictionary.find({o:'Let the game starts!'});
    }
}

在上面我假设你有autopublish包(默认情况下,当你创建一个包时,这应该不会真的打扰你,但以防你被删除)

使用您的文档标题,您必须使用稍微不同的实现,因为记住在Meteor.startup运行时不会下载数据,因为首先下载html和javascript&amp;数据为空,然后数据缓慢进入(然后反应性地填充数据)