Samuel Jansson
Samuel Jansson

Reputation: 327

How to get _id value in Meteor template

Here is my template snippet.

{{#if is_multiple_choice _id}}
  <div class="row" style="margin-bottom: 20px;">
    <div class="input-field col s11">
      <select id="ans_{{_id}}" name="answer" class="multiple_choice_answer">
        <option value="">No Answer Given for Multiple Choice</option>
      {{#each allowed_values}}
        {{#if matched value _id}}
          <option value="{{value}}" selected>{{value}}</option>
        {{else}}
          <option value="{{value}}">{{value}}</option>
        {{/if}}
      {{/each}}
      </select>
      <label>{{text}}</label>
    </div>
  </div>
{{/if}}

So I aimed to use _id in "matched" helper, but it seems the _id in matched value _id line gets nothing.

How can I get _id and use it in "matched" helper?

Please help me!!!

Upvotes: 2

Views: 759

Answers (1)

MrE
MrE

Reputation: 20788

Within the {{#each}} {{/each}} loop, you are in a child context

To access the parent context, you need to use the .. notation, like this: ../_id.

You can also use this within a Template.helper to get this._id:

Template.example.helper({
    "id": return this._id;
});

You can then use id anywhere in the Template.

Note:

1) this._id is equivalent to Template.instance().data._id within a helper.

Use Template.instance().data to access the template data context within an event, onCreated or onRendered.

2) The .. notation can be used to access the grand-parent template as well, with ../../_id for example.

This .. pattern is acceptable to access parent context from a {{#each}} loop within the same Template for example, but it is not recommended to use with child templates (to access parent template) because your child template is not reusable without the parent template context.

Upvotes: 2

Related Questions