Get element from array from html-file [solved]

I’m using meteor (version 1.8) with blaze.js and mongodb.

I’m trying to use an array-element which looks like this on the html file:

{{#each name in chatMeta.lastWhisp}}
 <div class="WhisperCharacter">
  {{name}}  
 </div>
{{/each}}

The corresponding helper for this query looks like this:

chatMeta() {
return ChatMeta.findOne({});
},

The collection that gets queried has an array “lastWhisp”

"lastWhisp": ["StringA", "StringB"]

I’m trying to get the information of {{name}} with an event handler:

  'click .WhisperCharacter'(event, template) {
    alert(this.name); //<- Wrong
  },

Normally, I’m able to retrieve the data with “this.x” on the {{each}}-handlebar, but that only seems to work if I query whole documents each, not with an array inside one single document.

I tried a lot of funky stuff like this.lastWhisp.name etc. basically guessing. I can’t get behind what it needs to retrieve the information of that {{each}}-handlebar. Could someone help me out with how it works in this case?

Thank you!

Have you tried something such as using a let block?

{{#let chatMetaObj=(chatMeta)}}
  {{#each name in chatMetaObj.lastWhisp}}
    <div class="WhisperCharacter">
        {{name}}  
    </div>
  {{/each}}
{{/let}}
1 Like

Thank you, but Jankapunkt from Github gave me a somewhat simpler solution:

Ah yes, I thought you were just having a hard time accessing all the elements of the array. You can easily alert them that way. Below is the same let scope with the added data attr

{{#let chatMetaObj=(chatMeta)}}
  {{#each name in chatMetaObj.lastWhisp}}
    <div class="WhisperCharacter" data-name="{{name}}">
        {{name}}  
    </div>
  {{/each}}
{{/let}}

Actually I use those alerted data for an reactive variable. The alert was just a test.

But just to learn more about your method: If I would do it with {{let}} I could use this.name ?

let forms a data context in blaze:
http://blazejs.org/guide/spacebars.html#Let

If you want those values to be accessible in the this context you would want to make another template and have this all handled in there such as below

either below your closing of your current template or another file:

<template name="newTemplateNameHere">
    <div class="WhisperCharacter" data-name="{{name}}">
  ....
    </div>
</template>

Then in your current template:

{{#let chatMetaObj=(chatMeta)}}
  {{#each name in chatMetaObj.lastWhisp}}
        {{> newTemplateNameHere name=(name) }}  
  {{/each}}
{{/let}}

and in the Js for the new template:

Template.newTemplateNameHere.events({
  'click .selectorHere': function(e, template) {
   const name = Template.currentData().name;
  // or
  const otherWayToGetName = template.data.name;
  }
})
1 Like

Oh wow, I didn’t even think that far. This is really smart. Thank you!