Search code examples
meteormeteor-blaze

How can I assign unique IDs to DIVs generated from multidimensional array in Meteor/Blaze


I need a unique id for each div on my page. Right now I was assigning it in the helper with Random.id(), but I just realized that the id changes on rerender (duh!).

How can I get a static unique id? I know I need a counter, but I don't know how to do it with Blaze.

Here is my html:

<template name="article">
    <article>
        <h2>{{title}}</h2>
            {{#each paragraphs}}
                {{> paragraph }}
            {{/each}}
    </article>
</template>
<template name="paragraph">
    <div class="container paragraph">
        {{#each sentences}}
            {{>sentence}}
        {{/each}}
    </div>
    <BR><BR>
</template>
<template name="sentence">
    <span>
        {{#each forward.words }}
            {{> word }}
        {{/each}}
    </span>
</template>
<template name="word">
    {{#with theWord}}
        <div id="{{divID}}" class="word nonPopped" data-wordID="{{_id}}">
            <p class="pinyin thinnerBottom text-muted score{{score}}">{{pinyins.[0].pīnyīn}}</p>
            <h3 class="thinnerTop ">
                <a style="color: black;" href="#">
                    {{#each characters}}
                        {{>character}}
                    {{/each}}
                </a>
            </h3>
        </div>
    {{/with}}
</template>
<template name="character">
    {{#with theCharacter}}
        <span id="{{spanID}}" class="character thinnerTop">{{simplified}}</span>
    {{/with}}
</template>

Solution

  • Here is what seems to be working:

    Template.word.onCreated(function () {
        this.data.divID = Random.id(6)
    })
    
    Template.word.helpers({
    theWord: function () {
        var theWord = Words.findOne({_id: this.wordID})
    ...
            if (!theWord.divID) {
                theWord.divID = this.divID
            }
            return theWord
        }
    })
    

    If upon further testing this doesn't work, I will delete this answer.