Search code examples
mustacheamp-htmlamp-mustache

AMP: How to handle complex conditional logic in AMP?


We want to insert some conditional dynamic content on our AMP pages. We are using mustache to add the dynamic content.

Mustache is logic less (with support for basic if else) i.e. mentioned here. They have also suggested to use Handlebar JS for such complex conditional logic but looks like we don't have any AMP alternative here.

One way to solve is - send simple boolean from server to avoid all AND/OR conditions on the client side but we will have to send too many such variables if we go by this approach. How should we handle such complex conditions in AMP?


Solution

  • For more complex use cases you can combine amp-bind and amp-list. The trick is: bindings are evaluated as part of amp-list rendering. This means you can use the expressiveness of amp-bind together with mustache template logic:

      <amp-state src="amp-list-state.json" credentials=include id=state></amp-state>
      <amp-list  src="amp-list-state.json" credentials=include height="560" layout="fixed-height"   >
         <template type="amp-mustache">
           <li>{{.}}
              <div [hidden]="state.user.likesPickups">
                Convertibles ...
             </div>
             <div [hidden]="!state.user.likesPickups && state.user.age < 30">
                Pickups  ...
             </div>
           </li>
        </template>    
      </amp-list>
    

    Note: it's best to use the same JSON endpoint for both amp-state and amp-list. This ensures that only a single request will be made during page load.

    Link to the sample: https://amp-demos.glitch.me/amp-list-state.html