【问题标题】:Looping assets and entries together将资产和条目循环在一起
【发布时间】:2017-08-26 22:35:00
【问题描述】:

我已经设法循环出特定 ContentType 中的所有内容,并且一切正常,除了条目后面没有它们的特定资产。

在这种特定情况下,它呈现为: 条目 1 条目 2 条目 3 资产 1 资产 2 资产 3

我希望它呈现为:条目 1 资产 1、条目 2 资产 2 等...

将资产数组循环放在字段循环中没有帮助:)

Javascript

client.getEntries({
    include: 1,
    'content_type': 'posts'
})
.then((response) => {

    var template = $('#myEntries').html();
    var html = Mustache.to_html(template, response.toPlainObject());
    $('.result').html(html);

})
.catch((error) => {
    console.log('Error occured')
    console.log(error)
})

HTML

<script id="myEntries" type="text/template">
    {{#items}}
        <h1>{{fields.header}}</h1>
        <p>{{fields.description}}</p>
    {{/items}}

    {{#includes.Asset}}
        <p>File: <img src="https:{{fields.file.url}}?fit=thumb&f=top_left&h=200&w=200" width="100"/></p>
    {{/includes.Asset}}
</script>

<div class="result"></div>

JSON https://jsfiddle.net/pcgn73zf/

希望得到您的帮助!

【问题讨论】:

    标签: javascript jquery json api contentful


    【解决方案1】:

    你在用 response.toPlainObject() 奉承 JSON。尝试按所需的顺序读取所需的属性。

    例子:

    var input = {
      entries: [
        {
          text: "Entry 1"
        },
        {
          text: "Entry 2"
        }
      ],
      assets: [
        {
          text: "Asset 1"
        },
        {
          text: "Asset 2"
        }
      ]
    };
    
    var i = 0;
    while (i < Math.max(input.entries.length, input.assets.length)) {
      if (i < input.entries.length) {
        document.write(input.entries[i].text + ", ");
      }
      if (i < input.assets.length) {
        document.write(input.assets[i].text + ", ");
      }
      i++;
    }

    【讨论】:

      【解决方案2】:

      您好,也许您在文档中错过了它,但内容型 js SDK 已经进行了链接解析,例如,如果您有一个包含图像字段的 contentType 帖子,当您获得条目时,您可以直接访问资产的字段.所以要从链接资产中获取url,您只需请求myEntry.fields.image.fields.file.url。无需请求它的表格包括。 您代码中的资产部分应该是(假设资产字段称为图像)

       <p>File: <img src="https:{{fields.image.fields.file.url}}?fit=thumb&f=top_left&h=200&w=200" width="100"/></p>
      

      请注意,链接解析仅在请求收集端点 client.getEntries() 时有效 有关更多信息,请查看此自述文件section

      【讨论】:

      • 我已经阅读了有关链接解析的信息,但没有得到它的目的!再次感谢队友。完美运行。
      猜你喜欢
      • 2013-03-22
      • 1970-01-01
      • 2018-06-22
      • 1970-01-01
      • 2013-12-04
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多