2013-10-02 153 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