0

With the conventional use of a dom-repeat loop and a template, the field reference is hard-coded against the source object. In the example below we're pulling the name and description fields from a JSON object. Works fine.

 <template is="dom-repeat" items="[[subjects]]">
      {{item.name}},  {item.description}}
 </template>

In my application I'd like to pull values programmatically by using a nested template that loops through a supplied list of fields. However I'm not able to make it work, the results come out as literal text rather than performing as I'd like:

 <template is="dom-repeat" items="[[subjects]]">
      <template is="dom-repeat" items="[[fields]]" as="field">
            {{item.{{field}}}},
      </template>
 </template>

These are the variations I've tried and the results using 'name' and 'description' as the fields:

   {{item.{{field}}}},      ->  "{{item.name}}  {{item.description}}"
   {{item[ {{field}} ]}},   ->  "{{item[ name ]}}   {{item[ description ]}}"

Ideally, I would like it to work like this:

    someFunction( {{item}}, {{field}} )

Where someFunction would take in the object & field specifier and return a string.

Just not sure how to make it happen. Any ideas?

Addendum showing missing parts called out:

<iron-ajax>
      auto         
      url="https://api.github.com/users/burczu/repos"
      params='{"type":"all"}'
      handle-as="json"
      on-response="handleResponse">
</iron-ajax>

and

<script>

    class MyElement extends Polymer.Element {

      static get is() { return 'my-element'; }

      static get properties() {
        return {
            subjects: { type: Array },
            fields: { type: Object }
            };
        }

        ready() {
           super.ready();
           this.fields = JSON.parse('{"show": ["name", "description"] }').show;
        }

        handleResponse(data) {
            this.subjects = data.detail.response;
        }
    }

    window.customElements.define(MyElement.is, MyElement);
  </script>
Brian
  • 372
  • 1
  • 4
  • 12

1 Answers1

0

Ok, the solution isn't far off from what I wanted. It was a matter of applying the right syntax:

<template is="dom-repeat" items="[[subjects]]">
      <template is="dom-repeat" items="[[fields]]" as="field">
            [[ _formatText(item, field) ]],
      </template>
 </template>

<script>
     class MyElement extends Polymer.Element {
        . . .
        _formatText(obj, field) {
            return obj[field];
            }
        . . .
       }
</script>

While it works as I wanted, all text returned by the _formatText function will be rendered as an HTML-safe string outside of the square brackets. No chance of emitting tags recognized by the browser. :(

If anyone knows how to get over that hurdle, please let me know.

Brian
  • 372
  • 1
  • 4
  • 12
  • 1
    This solution for [rendering entity symbols in dom-repeat](https://stackoverflow.com/a/49263056/1316011) might help. – Thad May 05 '18 at 15:08