2

I'm trying to use a dom-repeat inside a dom-repeat over a json array inside a json array. How can pass a value from the first array over to the second dom-repeat?

To illustrate, I have the following json array which loads fine:

  "books": [
    {
      "title": "book1",
      "slug": "b1",
      "authors": ["author1","author2"],
      "blurb": "Some text"
    },
    {
      "title": "book2",
      "slug": "b2",
      "authors": ["author2","author3"],
      "blurb": "some more text"
    }]

I'm iterating over the array 'books' and retrieve title and blurb. Then underneath, I want both authors of each book listed and I also want a link to each one in the format of /slug/author (f.i. /b1/author1). But because in the second dom-repeat I redefine "items", the 'slug' is no longer available. How do I go about this?

<template>
    <iron-ajax
      auto
      url="somelist.json"
      handle-as="json"
      last-response="{{someList}}"></iron-ajax>

    <template is="dom-repeat" items="{{someList.books}}">
         <paper-collapse-group>
           <paper-collapse-item header$="{{item.title}}">
               <p>{{item.blurb}}</p>
           </paper-collapse-item>
           <template is="dom-repeat" items="{{item.authors}}">
                  <a href$="/[[slug]]/[[item]]">{{item}}</a></div>
           </template>
         </paper-collapse-group>
    </template>
</template>

I'm also very new to Polymer so thank you for helping me learn!

Vims
  • 157
  • 1
  • 8

2 Answers2

5

Use the as attribute to use a custom name for the item property.

Example:

<template>
    <iron-ajax
      auto
      url="somelist.json"
      handle-as="json"
      last-response="{{someList}}"></iron-ajax>

    <template is="dom-repeat" items="{{someList.books}}" as="book">
        <paper-collapse-group>
          <paper-collapse-item header$="{{book.title}}">
              <p>{{book.blurb}}</p>
          </paper-collapse-item>
          <template is="dom-repeat" items="{{book.authors}}" as="author">
                  <a href$="/[[book.slug]]/[[author]]">{{author}}</a></div>
          </template>
        </paper-collapse-group>
    </template>
</template>
danielx
  • 1,785
  • 1
  • 12
  • 23
1

So what you can do is to create another element, let's say that would look like:

<dom-module id="authors">
  <template>
    <template is="dom-repeat" items="[[authors]]">
      <a href$="/[[slug]]/[[item]]">[[item]]</a>
    </template>
  </template>

  <script>
    Polymer({
      is: 'authors',

      properties: {
        authors: Array,
        slug: String
      },
    });
  </script>
</dom-module>

and then inject it into your code like:

<template is="dom-repeat" items="[[someList.books]]">
  <paper-collapse-group>
    <paper-collapse-item header$="[[item.title]]">
      <p>[[item.blurb]]</p>
    </paper-collapse-item>
    <authors slug="[[item.slug]]" authors="[[item.authors]]"></authors>       
  </paper-collapse-group>
</template>
Kyle
  • 184
  • 2
  • 13