Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I grab the current template within the javascript console?

if you have an onRendered callback, you can log the this to get the template.

Template.myTemplate.onRendered(function () {
  console.log(this);
});

For debugging purposes, in the javascript console, is it possible to get the current rendered template via some sort of script? Eg:

> var ctx = Template.myTemplate  // something like this
like image 991
corvid Avatar asked Dec 09 '22 03:12

corvid


2 Answers

In Chrome (and possibly other browsers), after you console.log an object, you can right click on the output in the JavaScript console and click "Store as global variable". That will assign it to a variable (named temp1, temp2, and so on). You can then access that object through the new variable.


Also in Chrome, selecting an element in the developer tools makes it available in the JavaScript console as $0. If you define the following function globally:

getTemplateInstance = function (elem) {
  var view = Blaze.getView(elem);
  while (!view.templateInstance) {
    view = view.parentView;
  }
  return view.templateInstance();
}

Then you can get any rendered template instance by following these steps:

  1. Right click somewhere on the template
  2. Click "Inspect element"
  3. In the developer tools, switch to the JavaScript console
  4. Enter getTemplateInstance($0) to get the template instance.

If you're careful to only select an element at the top level of the template (not inside a {{#if}}, {{#each}}, etc.) then you can skip the getTemplateInstance function and just run Blaze.getView($0).templateInstance() in the console.

You can also use Blaze.getData($0) to get the data context of an element.

like image 77
user3374348 Avatar answered Dec 11 '22 11:12

user3374348


Because its possible to have two of the same template you have explicitly pass on its reference to a global variable.

ctx = null;

Template.myTemplate.onRendered(function () {
    ctx = this;
});

This should let you use 'ctx' anywhere. It depends a lot on where you use it, you can get the template instance in events or helpers you can get the template instance from within its own helpers or events:

Template.myTemplate.events({
    'click #something': function(e,tmpl) {
         console.log(tmpl) //The template instance
         console.log(Template.instance())  //just like tmpl
     }
});

Template.myTemplate.helpers({
    'somehelper': function() {
         console.log(Template.instance());
     }
});
like image 31
Tarang Avatar answered Dec 11 '22 09:12

Tarang