rda3000
rda3000

Reputation: 1420

passing parameters to template helpers

In Discover Meteor, there's a point where we pass a parameter (title or url) to a template helper like this:

<div class="form-group {{errorClass 'title'}}">
...
...
<div class="form-group {{errorClass 'url'}}">

Then we define helpers that are aware of the parameter being passed, like this:

errorClass: function (field) {
  return !!Session.get('postSubmitErrors')[field] ? 'has-error' : '';
}

The Session.get('key')[parameter]syntax is confusing to me - why is the parameter not passed with the key, but outside the function, surrounded by brackets? I don't see examples of this syntax in the docs. Thanks.

Upvotes: 0

Views: 173

Answers (1)

11684
11684

Reputation: 7517

So, in JavaScript we can access properties of an object like this:

foo.bar

This means:

  1. get the object in the variable foo
  2. extract the property called bar.

There exists an alternative syntax:

foo["bar"]

This means exactly1 the same.

Why do we need this alternative syntax? Well, it allows us to do cool things like this:

var foo = { bar: "Nero", baz: "Caligula"}
var field = "bar";
foo[field]; // Evaluates to "Nero"
field = "baz";
foo[field]; // Evaluates to "Caligula"

(and it is how indexing into an array works).

This can be easily extended to:

function accessFoo(field) {
    return foo[field]; // with foo from previous example.
}
accessFoo("bar"); // evaluates to "Nero"
accessFoo("baz"); // evaluates to "Caligula"

I hope you can see the similarity of your code sample and my last example.

1: for practical purposes - maybe there are some slight differences. If so, I'd love to hear about them in the comments.

Upvotes: 1

Related Questions