1

I have a game and I want a system that renders a template if they have any adventures left.

Meteor.methods({


  adventure: function () {
    if(Meteor.user().adv > 0)
    {
    Meteor.users.update({_id: this.userId}, {$inc: {'adv': -1 }}); 
    this.render('adv');
    }
    else
    {
    this.render('noadventures');
    }
  },      
})

I have a template named adv but It wont load..

Alex Hong
  • 95
  • 9
  • are you using autopublish? my first guess is that (if you arent) you aren't publishing/subscribing all of the current user's data. Does it always render the "noadventures" template? have you set up routes using ironrouter? If so, what do those look like? – Ramsay Lanier Mar 06 '15 at 18:54
  • I don't want these templates to actually be accesible by url.. Is there a way to have the js just render a template in the html? – Alex Hong Mar 06 '15 at 19:13

2 Answers2

1

Use Blaze.render or Blaze.renderWithData - like so:

Meteor.methods({


  adventure: function () {
    if(Meteor.user().adv > 0)
    {
    Meteor.users.update({_id: this.userId}, {$inc: {'adv': -1 }}); 
       Blaze.render(Template.adv, $('body').get(0);
    }
    else
    {
       Blaze.render(Template.noadventures, $('body').get(0);
    }
  },      
})

You can do more with this - the documentation is pretty good.

Ramsay Lanier
  • 426
  • 6
  • 18
1

Some backgroud info: one of the Meteor principles is "data on the wire", meaning only the bare neccessities are sent to the client (the actual data), so you can't compile templates on the server and send them to the client. Sure technically this is possible and there are scenarios you want this (for example when sending html emails), but generally it's a bad idea.

Calling a Blaze render function inside a Meteor method won't work, because Blaze runs on the client side, and your method is on the server side. You should render in Meteor.call on the client side like this:

Meteor.methods({
  adventure: function () {
    if(Meteor.user().adv > 0) {
      Meteor.users.update({_id: this.userId}, {$inc: {'adv': -1 }});
      return true;
    }
    return false;
  }
});

And on the client side:

Meteor.call('adventure', function (error, result) {
  if (error) {
    // do something
  }
  else {
    if(result)
      Blaze.render(Template.adv, $('body').get(0);
    else
      Blaze.render(Template.noadventures, $('body').get(0);
  }
}

Why do you need to call Blaze.render? Why don't you just do this in the template, something like

{{> Template.dynamic template=template}}
Sander van den Akker
  • 1,545
  • 11
  • 13