How to exclude an array/object element with Handlebars?

送分小仙女□ 提交于 2019-12-12 04:04:49

问题


Right now I have this json structure

"administration" : [
  {
    "name" : "Sigfried Bermudez",
    "role" : "Associate Director"
  },
  {
    "name" : "Karen Madrigal",
    "role" : "QA Manager"
  },
  {
    "name" : "Jorge Lopez",
    "role" : "Project Manager"
  }
]

as you see the last element in that array says "role" : "Project Manager", and the way I am excluding this element from the view is this

{{#each chart-container.[3].administration}}
     {{#unless @last}}
          <span>{{@key}} {{this.name}}</span>
     {{/unless}}
{{/each}}

but what about that element changes the position?

what I need to know is if I can do something like {{#unless this.role.toLowerCase().indexof("project")}} or what is the best option in this case? if there is a way to do this from the HTML, it would be awesome :)


回答1:


Working example: JsFiddle

Use Handlebars helper:

var entry_template = document.getElementById('entry-template').innerHTML;
var data = [
  {
    "name" : "Sigfried Bermudez",
    "role" : "Associate Director"
  },
  {
    "name" : "Karen Madrigal",
    "role" : "QA Manager"
  },
  {
    "name" : "Jorge Lopez",
    "role" : "Project Manager"
  }
]

Handlebars.registerHelper("ifvalue", function(conditional, options) {
  if (conditional !== options.hash.notequals) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
});

var template = Handlebars.compile(entry_template);
var template_with_data = template(data);

document.getElementById('data').insertAdjacentHTML('afterbegin', template_with_data);

Template:

<script id="entry-template" type="text/x-handlebars-template">
  {{#each this}} 
    {{#ifvalue this.role notequals="Project Manager"}} 
        {{this.name}} 
    {{/ifvalue}} 
  {{/each}}
</script>
<div id="data">
</div>


来源:https://stackoverflow.com/questions/35702172/how-to-exclude-an-array-object-element-with-handlebars

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