Author

Alejandro Alcalde

Data Scientist and Computer Scientist. Creator of this blog.

Alejandro Alcalde's posts | Porfolio

Table Of Contents

What is Amp-mustache and how it works

Recently I have been implementing Google AMP pages in my site. Everything was going well until I decide to implement lists with amp-mustache. This component of AMP allows to populate elements from a json, for example one could create a list from this json:

{
  "items": [
    {
      "title": "amp-carousel",
      "url": "https://ampbyexample.com/components/amp-carousel"
    },
    ...
  ]
}

And then we have a template like this one to generate the content:

  <ul>
    <amp-list width=auto
        height=100
        layout=fixed-height
        src="https://ampbyexample.com/json/examples.json">
      <template type="amp-mustache"
          id="amp-template-id">
        <li>
          <a href="{% raw %}{{url}}{% endraw %}">{% raw %}{{title}}{% endraw %}</a>
        </li>
      </template>
    </amp-list>
  </ul>

This code would be populated from the json by replacing each {% raw %}{{tag}}{% endraw %} with its corresponding value in the json. Up until here all seems to be pretty easy, but when you are using Jekyll on your site things change a little. Lets see why.

How to make amp-mustache work in jekyll

In Jekyll there are liquid tags, and they have the same syntax amp-mustache templates have, so when jekyll is building the site, it will interpret each {% raw %}{{tag}}{% endraw %} in the example above as liquid variables. However, since this variables do not exists they will be left blank, and so the template would not be populated.

In my case, the error Missing URL for attribute 'src' in tag 'a'. came from this piece of code <a href={% raw %}{{url}}{% endraw %}>, because jekyll do not find any variable which name was url and in consequence leave it blank. To solve this problem we need to tell jekyll that those tags are not liquid tags. This is easily done with: {% raw %}{% raw %}{{ tag }}{% endraw %}{{ "{% endraw " }}%}. Knowing this, the code for generate a list with amp-mustache would be as follow:

  <ul>
    <amp-list width=auto
        height=100
        layout=fixed-height
        src="https://ampbyexample.com/json/examples.json">
      <template type="amp-mustache"
          id="amp-template-id">
        <li>
          <a href="{% raw %}{% raw %}{{url}}{% endraw %}{{ "{% endraw " }}%}">{% raw %}{% raw %}{{title}}{% endraw %}{{ "{% endraw " }}%}</a>
        </li>
      </template>
    </amp-list>
  </ul>

References

Spot a typo?: Help me fix it by contacting me or commenting below!

Categories:Tags: