jfjobidon
jfjobidon

Reputation: 327

Meteor: passing variable from server to client

I want to pass a variable from server side to a template in the client side. In main.html, I have this template:

<template name="hello">
  ...
  <p>{{privateKey}}</p>
</template>

In main.js, I want something like:

if (Meteor.isClient) {
    Template.hello.helpers({
        privateKey : function () {
            return 'call to function makePrivateKey';
        }
    });
}

if (Meteor.isServer) {
    Meteor.methods({
        makePrivateKey: function() {
            var privKey = bitcoinjs.ECKey.makeRandom();
            return privKey.toWIF();
        }
    });
}

How can I invoque the function makePrivateKey from server side and print the private key in my template ? I don't want to use session variable or dynamic variable.

Upvotes: 2

Views: 2396

Answers (2)

user2977636
user2977636

Reputation: 2296

In general using the Meteor 'Method' would be the way to go:

if (Meteor.isClient) {
  Template.hello.helpers({
    privateKey : function () {
      return Meteor.call(makePrivateKey);
    }
  });
}

Upvotes: 1

ffxsam
ffxsam

Reputation: 27793

Seems like a strange structure to me. You wouldn't want a helper to generate a private key, I don't think. Every time that template renders, it would generate a key and print it. But you couldn't just call the method like this anyway, as using Meteor.call on the client requires a callback, and so again, this is not the way to do this. However, this could work:

if (Meteor.isClient) {
  Template.hello.events({
    'click .generate-key': function () {
      Meteor.call('makePrivateKey', function (error, result) {
        if (!error) {
          Session.set('credentials/privKey', result.privKey);
        }
        else {
          // handle error
        }
      })
    }
  });

  Template.hello.helpers({
    privateKey: function () {
      return Session.get('credentials/privKey');
    }
  });
}

if (Meteor.isServer) {
  Meteor.methods({
    makePrivateKey: function () {
     try {
       var privKey = bitcoinjs.ECKey.makeRandom();
       return {privKey: privKey.toWIF()};
     } catch (e) {
       throw Meteor.Error('some-error', 'Bad things happened.');
     }
    }
  });
}

Upvotes: 2

Related Questions