Search code examples
amp-html

How to mix the result of multiple json data sources in AMP?


I'm outputting a list of links in which I need to mix values in the template coming from not one, but two individual JSON data sources.

Pseudo markup:

<a href="{link1}/{link2}">{title1}</a>

In the example above, link1 and title1 would come from JSON #1, whilst link2 would come from JSON #2.

To be clear: I know this challenge can be entirely avoided by merging the JSON data sources into a single service, yet in my scenario this is not possible, reasons aren't relevant.

Expanding a bit more on the total idea, the above pseudo markup I'm wrapping into an amp-list:

<amp-list id="mylist" width="auto" height="160px" layout="fixed-height" src="//json1">
    <template type="amp-mustache">
        <a href="{{buyURL}}={{UID}}">
           <amp-img src="{{logoURL}}" width="{{logoWidth}}" height="{{logoHeight}}" layout="fixed" alt="{{name}}">
            </amp-img>
         </a>
    </template>
</amp-list>

I've removed attributes irrelevant for the question. In the above code, all variables are coming from json1, except for the {{UID}} one. This one needs to come from a separate json service, let's call it json2 for now.

My challenge is therefore to integrate a value coming from a 2nd data source and mixing it into the template output binded to the first data source. Here's what I have tried:

  • Nesting templates within each other does not seem allowed, it throws an AMP error
  • Nesting lists is allowed, yet you can only put the template within the hierarchy of the correct list. Putting them on the same level makes AMP simply pick the first or throw an error "template not found".

I am stuck in implementing the above scenario. I don't know how to approach it, or where it is at all possible.


Solution

  • Self-answering my question. Note that this answer is hugely inspired by the other answer of Sebastian Benz, yet with some small changes.

    <amp-state id="requestID">
      <script type="application/json">
        {
        "unid": "123654"
        }
      </script>
     </amp-state>
    
     <amp-list id="mylist" width="auto" height="160px" src="//.." items="..">
        <template type="amp-mustache">
           <a href="" [href]="'{{URL}}&id=' + requestID.unid">{{name}}</a>
        </template>
     </amp-list>
    

    In the above example, {{URL}} and {{name}} come from the amp-list JSON source, whilst requestID.unid comes from a second JSON source. The syntax shows how to concatenate both data sources into a single attribute: href. Key differences from the other answer given are:

    • href should be empty, not assigned {{URL}}
    • expression in [href] should not assign variable, it should evaluate a return value instead