在聚合物2嵌套模板中以编程方式访问对象值



常规使用DOM重复循环和模板,该字段参考是针对源对象进行了硬编码的。在下面的示例中,我们从JSON对象中提取名称和描述字段。工作正常。

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

在我的应用程序中,我想通过使用一个嵌套模板通过提供的字段列表循环。但是我不是能够使它起作用,结果是作为字面文本而不是按照我想要的:

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

这些是我尝试过的变体,并且使用"名称"one_answers"描述"的结果作为字段:

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

理想情况下,我希望它像这样工作:

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

某种函数将在对象中摄取的地方&amp;字段说明符并返回字符串。

只是不确定如何实现它。有什么想法吗?

附录显示丢失的零件被调用:

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

<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>

好吧,解决方案与我想要的不远。这是应用正确语法的问题:

<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>

尽管它按照我的意愿工作,但_formattext函数返回的所有文本都将呈现为方括号外部的HTML-SAFE字符串。没有机会发出浏览器认可的标签。:(

如果有人知道如何克服这个障碍,请告诉我。

最新更新