Search code examples
javamustachehandlebars.js

Using the value from a map as a key to another value in the map of a mustache template


I'm using the jknack Java port of Handlebars. I need to create an A-Z list. The key to the map is a letter of the alphabet. At the moment, I have 26 of these in the mustache template:

{{#if A}}<li><a href="#a">A</a></li>{{else}}<li class="unused-letter">A</li>{{/if}}

It would be nice of I could add an array of the letters to the model under the key "keys", for example, and loop through the results:

{{#keys}}
   {{#if .}}<li><a href="#a">{{.}}</a></li>{{else}}<li class="unused-letter">{{.}}</li>{{/if}}
{{/keys}}

However, this doesn't check to see if the map has a key matching the value of the period.

Is there a way of using a value obtained from the map as the key to another object in the map?

Updated information

Looking at Mark's entry I can see that I was approaching the problem from the wrong direction. My model didn't have an entry in the Map if a letter had no results. However, if I update my model so that a key (letter) has an empty list rather than no key/entry at all then I can just use the keys on the Map rather than trying to use another entry to provide values that could represent all possible keys.


Solution

  • I'm not sure what your index data format looks like, so imagine the index was in JSON in this format:

    {
       "items":[
          {
             "A":[]
          },
          {
             "B":[
                "dummy",
                "dummy",
                "dummy"
             ]
          },
          {
             "C":[]
          },
          {
             "D":[
                "dummy",
                "dummy",
                "dummy"
             ]
          },
          {
             "E":[]
          },
          {
             "F":[
                "dummy",
                "dummy",
                "dummy"
             ]
          }
       ]
    }
    

    Now to iterate through displaying used/unused indexes would require a template like:

    <ul>
    {{#items}}
    {{#each .}}
    {{#if .}}
      <li><a href="#{{@key}}">{{@key}}</a></li>
    {{else}}
      <li class="unused-letter">{{@key}}</li>
    {{/if}}
    {{/each}}
    {{/items}}
    </ul>
    

    which for the above example data would result in:

    <ul>
      <li class="unused-letter">A</li>
      <li><a href="#B">B</a></li>
      <li class="unused-letter">C</li>
      <li><a href="#D">D</a></li>
      <li class="unused-letter">E</li>
      <li><a href="#F">F</a></li>
    </ul>