如何在AMP的amp-list模板中混合多个JSON数据源的字段?
I get it—you're stuck trying to pull a value from a second JSON source into an amp-list template that's already bound to a primary JSON feed, and merging the two data services isn't an option. Let's break down the correct approach here, since nested templates/lists aren't going to work as you've discovered.
The Key: Use amp-state to Preload Your Second JSON Data
AMP allows you to preload external data into a global state container using <amp-state>, which your amp-list template can then reference directly. This is perfect for your scenario where you need a single value (like UID) from a separate JSON service.
Step-by-Step Implementation
Add the
amp-statecomponent to your page
You'll need to include theamp-statescript in your document's<head>:<script async custom-element="amp-state" src="https://cdn.ampproject.org/v0/amp-state-0.1.js"></script>Preload your second JSON source into
amp-state
Define an<amp-state>element that fetchesjson2and stores its data. Assumingjson2returns a structure like{"UID": "your-unique-id"}, this would look like:<amp-state id="secondaryData" src="//json2"></amp-state>Update your
amp-listtemplate to reference the state value
In your template, replace the{{UID}}placeholder with a reference to the preloaded state value. AMP Mustache templates can access globalamp-statedata using the state ID:<amp-list id="mylist" width="auto" height="160px" layout="fixed-height" src="//json1"> <template type="amp-mustache"> <a href="{{buyURL}}={{secondaryData.UID}}"> <amp-img src="{{logoURL}}" width="{{logoWidth}}" height="{{logoHeight}}" layout="fixed" alt="{{name}}" > </amp-img> </a> </template> </amp-list>
Important Notes
- Data Loading Order: AMP will handle dependencies automatically, but if your second JSON loads slower than the first, there's a chance the
UIDmight be missing when theamp-listfirst renders. If this is a problem, you can use AMP Bind to delay theamp-list's data fetch until theamp-stateis loaded. For example:
This way, the<amp-list id="mylist" width="auto" height="160px" layout="fixed-height" [src]="secondaryData.UID ? '//json1' : ''" src="" > <!-- template remains the same --> </amp-list>amp-listonly fetchesjson1oncesecondaryData.UIDis available. - Multiple Values from
json2: Ifjson2returns an array instead of a single object, you'd need to adjust the reference (e.g.,secondaryData.items[0].UID), but since you mentioned needing justUID, this shouldn't be an issue.
Why Your Previous Attempts Didn't Work
- Nested Templates: AMP explicitly doesn't allow nested Mustache templates inside
amp-list, so that approach will always throw an error. - Nested Lists: While you can nest
amp-listelements, each list's template can only access data from its ownsrcfeed—you can't cross-reference data between parent/child lists in the way you need.
内容的提问来源于stack exchange,提问作者Fer

