Dust - how to get parent context in loop

1.1k Views Asked by At

I am trying to retrieve values in a loop from the parent context. Dust is able to call my method, but my method is not able to reach my properties which I have defined in the class, due to the context is the current item.

So for example:
JavaScript class

MyNamespace.MyClass = function () {
   this.names= ["Me", "You", "StackOverflow"];
   this.isAwesome = true;
};

MyNamespace.MyClass.prototype.sayHello = function() {
   if(this.isAwesome) {
      return "Hello awesome ";
      // This code will never be reached due to 'this' is one of the items from the array
   }
   return "Hello "; 
};

My Dust

{#names}{sayHello} {.}{~n}{/names}

Problem
The sayHello method will be called as expected but the context is the current item instead of the parent. So this is equals to the current item and of course "Me".isAwesome will always return false. As you would understand, I would like to be awesome.

Question
How can I achieve that 3 awesome people are returned by dust.

2

There are 2 best solutions below

2
On

When you call a function using Dust, the function is invoked with the arguments chunk, context, bodies, params.

You can call context.get(name) to search the context stack for your desired variable.

{
  "sayHello": function(chunk, context, bodies, params) {
    if(context.get("isAwesome")) {
      return "Hello awesome";
    }
    return "Hello";
  },
  "names": ["One", "Two", "Three"],
  "isAwesome": true
}
0
On

You could pass the required contextual variable as a parameter:

{#names myvar=parentContextVariable}{sayHello x=myvar} {.}{~n}{/names}

And then, in the helper function:

"sayHello": function(chunk, context, bodies, params) {
    //use params.x
}

Yes, here also, your function will have the extra concern (of DustJs's presence).