bgmaster bgmaster - 1 month ago 7
Javascript Question

Programmatically insert variables into Meteor Templates with Blaze.render + Blaze.view or Blaze.with

I'm trying to figure out how to programmatically insert a variable helper into a template using the Blaze API. I believe it needs to be done using some form of:

Blaze.render(Blaze.with('variable', contentFunction);


However, I'm struggling to get the contentFunction to work properly. I tried a function that returns a Session variable:

var session_var = function() {
return Session.get('myVariable');
};


However, I keep getting undefined errors. I know this could be done if I defined a separate template to be rendered, but that seems a bit much for this particular case. I was wondering if someone could explain how Blaze.with and Blaze.view work. Also, is it possible to programmatically insert just a variable helper into a template?

Answer

Without knowing exactly what you're trying to do, it's not clear if this is the easiest way of going about things.

However, if you look at the docs, you'll see that you can either supply the session variable in a data context and use Blaze.With, or supply no data context and use Blaze.View instead (which appears to be what you're going for).

So, if you want to render a reactive data context, it has to be supplied in the first argument to Blaze.With. Try something like this:

var myView = Blaze.With(
  function() {
    return {
      foo: Session.get('foo')
    };
  },
  function() {
    return Spacebars.mustache([
      'the value of foo is ',
      this.lookup('foo')
    ]);
  }
);
Blaze.render(myView, document.body); // or whatever element you want to render it inside

Alternatively, for Blaze.View:

var myView = Blaze.View(
  function() {
    return 'the value of foo is ' + Session.get('foo');
  }
);
Blaze.render(myView, document.body); 

To be honest, the easiest way to learn about the structure of renderable content (which is the difficult bit if you're doing this programmatically) is to study the stuff that the Spacebars compiler churns out. In other words, find an interesting template/sub-template that's been generated from quasi-HTML, pick an element out of it and run Blaze.getView([ELEMENT])._render, then study the result.