adrdomeniconi
adrdomeniconi

Reputation: 21

How to access global data inside a inner template on Meteor Iron-router

I´m using the Iron-router package and I´m having a problem to access global data in templates. I have a router.js wich defines:

router.js

var addMyData = function() {
    this.data = {myProp: 'value'};
}
Router.before(addMyData);

It works fine. If I need to use that inside a "each" handlebar, I can access the data using:

myTemplate.html

<template name='myTemplate>
     {{myProp}} //Works fine!
     {{#each something}}
        {{../myProp}} //Also works fine!
     {{/each}}
</template>

Great. But, when I need to use a inner template, all the data on the outter template just vanish. Example:

myTemplate.html

<template name='myTemplate>
    {{myProp}} //Works fine!
     {{#each something}}
        {{> myInnerTemplate}}
     {{/each}}
</template>

<template name='myInnerTemplate>
    {{../myProp}} //Not works!
</template>

The weirdest thing is that all the data from the outerTemplate are vanished.

Is that a bug, or there is another pratice to achieve the same goal?

Thank you.

Upvotes: 2

Views: 513

Answers (1)

Geoffrey Booth
Geoffrey Booth

Reputation: 7366

I have a Handlebars helper I use in all my projects that is designed to address this issue, modified slightly from code at http://rockycode.com/blog/handlebars-loop-index/ (CoffeeScript):

Handlebars.registerHelper "iter", (context, options) ->
    fn = options.fn
    inverse = options.inverse
    ret = ""
    if context and context.length > 0
        i = 0
        j = context.length

        while i < j
            ret = ret + fn(_.extend({}, context[i],
                i: i
                context: context
                parent: @
                self: context[i]
            ))
            i++
    else
        ret = inverse(@)
    ret

Replace {{#each}} and {{/each}} in your templates with {{#iter}} and {{/iter}}, and you'll have new variables parent, context and self, as well as loop index i, available to you within your iter loop (and by extension, in the subtemplate).

So in your case, {{../myProp}} should be replaced by either {{self.myProp}} or {{parent.myProp}} (trial-and-error, one or the other should work). I doubt your issue is particular to Iron Router.

Upvotes: 1

Related Questions