AMP for emails: How to handle complex conditional logic in AMP for emails?

493 Views Asked by At

I have developed a code which retrieves json data from the backend server using amp-list. Based on one of the variable from the server, I want to have an if condition. Mentioned below an example of what I wish to accomplish:

<html ⚡4email data-css-strict>
<head>
  <meta charset="utf-8">
  <script async src="https://cdn.ampproject.org/v0.js"></script>
  <script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>
  <script async custom-element="amp-list" src="https://cdn.ampproject.org/v0/amp-list-0.1.js"></script>
  <style amp4email-boilerplate>body{visibility:hidden}</style>
  <style amp-custom>
    h1 {
      margin: 1rem;
    }
  </style>
</head>
<body>
  <amp-list template="list-template" src="https://random_server_link/get_x_value_and_y_value" layout="responsive">
    <template id="list-template" type="amp-mustache">
    {% if {{x}} == {{y}} %}
      <p>
          x == y
      </p>  
    {% elif {{x}} != {{y}} %}
      <p>
        x not equal to y
      </p>
    {% else %}
      <p>
        else condition
      </p>
{% endif %}
  </template>
  </amp-list>
  <h1>Hello, I am an AMP EMAIL!</h1>
</body>
</html>

The above code doesn't work and I need an alternative for the if-else condition.

Thanks

1

There are 1 best solutions below

0
On

For simple if/else testing the truthiness of a Mustache variable, you can use the section tag and the inverted section tag, as mentioned in the AMP documentation as well as the Mustache documentation. See How do I accomplish an if/else in mustache.js? for examples.

For anything more complex than a simple truthiness test (e.g., equality checks between two variables), you will have to push that logic to the server side. Mustache doesn't come with the ability to compare values or express any other binary relations between two variables. It's designed to be a logic-less template. Do the computation on the server side, convert it to simple bits that you can check using the section tag and inverted section tag in Mustache on the client side.