How to pass a template variable to a template helper function to preserve context?

∥☆過路亽.° 提交于 2020-01-11 10:23:30

问题


I may be using the wrong words to describe my issue so here is the (simplified) code I'm working with.

I'm happy to learn a better way to do this but what I'm currently trying to do is pass {{assigneeId}} to the template helper function called agentIs. The problem is that I can't find the correct way to pass the value.

<template name="ticket_list">
  {{#each tickets}}
    {{> ticket}}
  {{/each}}
</template>

<template name="ticket">
  <h3>{{title}}</h3>
  <p>{{assigneeId}}</p>
  {{> ticket_footer}}
</template>

<template name="ticket_footer">
  {{> agent_list}}
</template>

<template name="agent_list">
  <!-- {{assigneeId}} exists here as expected -->
  assigneeId: {{assigneeId}}
  <label for="agent">Agent</label>
  <select id="agent" name="agent">
    {{#each agents}}
      <!-- value passed: "{{assigneeId}}" -->
      <option value="{{_id}}" {{#if agentIs "{{assigneeId}}"}}selected{{/if}}>
        {{profile.name}}
      </option>
      <!-- value passed: undefined -->
      <option value="{{_id}}" {{#if agentIs assigneeId}}selected{{/if}}>
        {{profile.name}}
      </option>
      <!-- value passed: JSON.parse error -->
      <option value="{{_id}}" {{#if agentIs {{assigneeId}}}}selected{{/if}}>
        {{profile.name}}
      </option>
    {{/each}}
  </select>
</template>
Template.agent_list.agents = function() {
  return Meteor.users.find({"profile.is_agent": true}, {sort: {profile: 1}});
}

Template.agent_list.agentIs = function(assigneeId) {
  return this._id === assigneeId;
};

回答1:


The correct syntax would be :

{{#if agentIs ../assigneeId}}selected{{/if}}

The {{#each agents}} block helper introduces a new level in the template contexts tree (the new context corresponds to the current agent), this is why you need to "go back" from one level to properly reference the previous context where assigneeId resides.



来源:https://stackoverflow.com/questions/17936924/how-to-pass-a-template-variable-to-a-template-helper-function-to-preserve-contex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!