【问题标题】:How to translate templates in Meteor?如何在 Meteor 中翻译模板?
【发布时间】:2013-10-04 02:56:41
【问题描述】:

更新 现在我尝试在我的应用程序中执行此操作(感谢 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') 可以完美运行)

【问题讨论】:

    标签: meteor


    【解决方案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 并且数据是空的,然后数据进来很慢(然后反应性地填满数据)

    【讨论】:

    • DICTIONARY.insert({o: split[0], t:split[1]});我替换为 Dictionary.insert({o: split[0], t:split[1]});但在客户端 Dictionary.find().count() 仍然是 zer0
    • 您是否删除了自动发布功能?还有你在哪里运行Dictionary.find().count()?如果它在初始运行代码中的任何位置(不在模板帮助程序中),它将返回 0,因为客户端在运行时数据尚不可用(它在几毫秒后到达)
    • 是的,在我添加发布和订阅后,我的收藏被转移了,find({o: smth}) 有效。获取属性 t 我使用 .fetch()[0] THANKS
    • 仍然不能按我们的意愿工作:当模板被渲染时,字典是未定义的。
    • 您能否分享更多代码,我也不确定您的文本文件的结构,也可以使用 .fetch()[0] 代替 findOne() 你在浏览器 javascript 控制台中得到什么当你运行Dictionary.find().fetch()?
    猜你喜欢
    • 2015-09-25
    • 2016-05-02
    • 1970-01-01
    • 2012-11-13
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    相关资源
    最近更新 更多