tdj
tdj

Reputation: 143

Meteor.js / spacebars - Why does data context change when calling template with arguments/variables?

I have a child template, label:

<template name="label">{{name}}</template>

I include in a parent template (the data context of which defines name) like so:

A: <template name="parent">{{> label}}</template>

I want to set, e.g., the width, from the parent. To do so I provide it with an argument for width:

B: <template name="parent">{{> label width="100%"}}</template>

In B, the label template loses the data context of the parent and {{name}} is now undefined. In A, it maintains the data context and works fine. Why?

What can I do to fix this, other than this undesirable solution:

This works, but I don't want to do this:

<template name="parent">{{> label data=this width="100%"}}</template>
<template name="label">{{data.name}}</template>

Upvotes: 2

Views: 484

Answers (1)

Gaelan
Gaelan

Reputation: 1149

The argument passed to a template is the data context. If you don't pass an argument, the data context defaults to this, the current data context of the caller. Also, the label template won't use the width passed to it if you don't use it yourself. Fixed code:

<template name="parent">{{> label name=name width="100%"}}</template>
<template name="label"><span width={{width}}>{{data.name}}</span></template>

Upvotes: 4

Related Questions