Alex Rivera | Logout

Is there a way to pass variables into templates in Meteor?

Asked 2012-04-12T16:47:17.077
63

I've been experimenting with Meteor and ran into something I couldn't figure out. For fun, I was trying to make a slot machine. I had the following HTML:

<div class="slot-wrapper">
  {{> slot}}
  {{> slot}}
  {{> slot}}
</div>

<template name="slot">
  <div class="slot">
    <div class="number"><span>{{ number }}</span></div>
    <div class="divider"></div>
  </div>
</template>

I want to have a different number for each slot. Is it possible to pass variables into template? Something like this:

<div class="slot-wrapper">
  {{> slot 1}}
  {{> slot 2}}
  {{> slot 3}}
</div>

<template name="slot">
  <div class="slot">
    <div class="number"><span>{{ number i}}</span></div>
    <div class="divider"></div>
  </div>
</template>

Maybe I'm thinking about this the wrong way and there's a better way.

Edit
Report

1 Answer

9

I wanted to leave this as a comment, because it's just a clarification on Joc's answer, but couldn't, so here it is with plus the example I worked with.

Only ONE argument can be passed to the template :

{{> singleItemInfo arg1}}

this argument must be an object such as :

{
    number: 1,
    number2: 2,
    numberComposite: {
        subnum1: 10,
        subnum2: 20
    }
};

the argument values can be accessed via their keys, and the scope can be switched to get the subitems with the

{{#with numberComposite}}

Here's the full code for the example :

<html file>

<body>
    {{ itemsView }}
</body>

<template name="itemsView">
    {{> singleItemInfo arg1}}
</template>

<template name="singleItemInfo">
    arg1 = {{ number }}
    arg2 = {{ number2 }} 
    {{#with numberComposite}}
        subArg1 = {{ subnum1 }}
        subArg2 = {{ subnum2 }}
    {{/with}}
</template>

<javascript file>

Template.itemsView.arg1 = {
    number: 1,
    number2: 2,
    numberComposite: {
        subnum1: 10,
        subnum2: 20
    }
};

OUTPUT:

arg1 = 1 arg2 = 2 subArg1 = 10 subArg2 = 20 
answered 2012-11-02T02:47:28.423

Your Answer