2

I have managed to loop out all content from a specific ContentType and everything works well except that the entries are not followed by their specific assets.

In this specific case it renders as: Entry 1 Entry 2 Entry 3 Asset 1 Asset 2 Asset 3

I want it to render as: Entry 1 Asset 1, Entry 2 Asset 2 etc...

Putting the asset array loop inside the fields loop didn't help :)

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/

Would love your help!

4

2 回答 2

0

You are flattering JSON with response.toPlainObject(). Try reading required properties in desired order.

Example:

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++;
}

于 2017-04-01T20:24:25.973 回答
0

Hi maybe you missed it in the docs but the contentful js SDK already does link resolution, for example, if you have a contentType post that has an image field, when you get an entry you can access directly the fields of the asset. so to get the url from the linked asset you just request myEntry.fields.image.fields.file.url. No need to request it form includes. the asset part in your code should be (assuming that the asset field is called image)

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

Please note that link resolution only works when requesting the collection endpoint client.getEntries() for more infos check this README section

于 2017-04-01T21:13:35.317 回答