2013-10-02 88 views
0

修订 现在我尝试做这在我的应用程序(感谢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> 

Still无法正常工作:模板呈现时字典未定义。但是在控制台中的t('How to play')完美)

回答

1

Javascript变量不被客户端和服务器反应共享。你必须使用一个流星集合来存储你的数据,如

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首先下载&数据是空的,然后数据缓慢进入(然后反应性填充数据)

+0

DICTIONARY.insert({o:split [0],t:split [1]});我用Dictionary.insert替换({o:split [0],t:split [1]});但在客户端Dictionary.find()。count()仍然是zer0 – Vasiliy

+0

您是否删除了自动发布?另外你在哪里运行'Dictionary.find()。count()'?如果它在初始运行代码中的任何位置(不在模板帮助程序中),它将返回0,因为客户端在运行时尚未提供数据(它几秒后到达) – Akshat

+0

yeap,在我添加发布和订阅,我的收藏被转移,发现({o:smth})的作品。以获取属性我使用.fetch()[0] 感谢 – Vasiliy