Week 21 | Template Repeater

polymer 1.0
Tue Jan 17 2017

Another interesting and useful template type extension is the dom-repeat. The dom-repeat template will loop through the array items of the array given in the items attribute. Then we can get the index and the item in the loop.

Our first example is a simple loop of a messages array as you can see we loop through these items and display the index the value of those items.

Our second example is a bit more complex as our array has objects that contains arrays of themselves. So we can loop through these items. With the “as” attribute we can name the instance of the item every time in the loop and then we can add inner dom-repeat templates as well looping through arrays that are subproperties.

Lastly, with the index-as we can name the instance of the index. So this repeater will repeat through these items and then foreach of those it will repeat through the levels arrays as well, as you can see in our live preview.

[content_block slug=polymer-js-demo-of-the-week-footer]

<!DOCTYPE html>
<html>
    <head>
      <script src="https://polygit.org/polymer+:1.3.1/components/webcomponentsjs/webcomponents-lite.min.js"></script>
      <link rel="import" href="https://polygit.org/polymer+:1.3.1/components/polymer/polymer.html" />
    </head>
    <body>
    <alert-element></alert-element>
    <dom-module id="alert-element">
      <template>
        Messages:<br/>
        <template is="dom-repeat" items="{{messages}}">
          Index of message: {{index}}<br/>
          Message: <b>{{item}}</b><br/>
          ---------------<br/>
        </template>
        <template is="dom-repeat" items="{{messagePriorities}}" as="priority">
          <p>
            {{priority.name}}<br/>
            <template is="dom-repeat" items="{{priority.levels}}" as="level" index-as="level_index">
              {{level_index}} : {{level}}<br/>
            </template>
          </p>
        </template>
      </template>
    </dom-module>
    <script>
      HTMLImports.whenReady(function () {
        Polymer({
          is: "alert-element",
          properties:{
            messages:{
              type: Array,
              value: function(){
                return ["Message 1", "Message 2"];
              }
            },
            messagePriorities:{
              type: Array,
              value: function(){
                return [{name: "Major", levels: ["Super major", "Kind of a major"]},
                        {name: "Minor", levels: ["Minorish", "Good to have"]}
                       ];
              }
            }
          }
        });
      });
    </script>
    </body>
</html>

Full Stack Weekly Newsletter

A free weekly newsletter for full stack web developers!