How to implement simple AMP support in Drupal 8

Adding AMP support could be very tricky and complex depending on your project needs. In this blog post I won't be using AMP module. Instead I created something more simpler and easier to use for AMP integration. The Simple AMP module is still using Lullabot's AMP PHP library. The module is a starter module and most likely won't be very useful out of the box, but it can get you going very fast. It is available for download here.

Download from Github

First thing you need to do is install composer require lullabot/amp, the module won't work without it.

Once installed the module you might need to modify few lines of code:

  • Modify Drupal\simple_amp\AmpBase::getMetadata() to reflect data that you would like to show in AMP metadata.
  • Modify template in simple_amp/templates/amp.html.twig to match your design needs.
  • You may also have custom template per content type: amp--node.html.twig or amp--node--article.html.twig

By default Simple AMP module includes basic AMP javascript files. In order to add additional AMP JS files you will have to modify Drupal\simple_amp\AmpBase::detect() method. You would need to write some regular expressions to detect ads, youtube videos, vimeo, instagram or any other libraries. Once detected you would add that library to protected $scripts = [] array in the AmpBase class.

Example:

protected function detect() {
    $youtube = [
      '/youtube\.com\/watch\?v=([a-z0-9\-_]+)/i',
      '/youtube\.com\/embed\/([a-z0-9\-_]+)/i',
      '/youtu.be\/([a-z0-9\-_]+)/i',
      '/youtube\.com\/v\/([a-z0-9\-_]+)/i',
    ];
    foreach ($youtube as $regexp) {
      if (preg_match($regexp, $this->html)) {
        $this->scripts[] = '<script async custom-element="amp-youtube" src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script>';
      }
    }
  }

Roadmap

  • Improve UI
  • Eliminate any need for code modifications.

Feel free to create pull requests, help is always appreciated.