Forest header image

Symfony Finland
Random things on PHP, Symfony and web development

AMP theme for Twig and Symfony

AMP, the Accelerated Mobile Pages is an alternative markup to traditional HTML. Released in October 2015, the technology continues to gain popularity. In 2018 content driven sites should definitely look into integrating AMP markup views for optimal load times and SEO.

At it's heart the srouce AMP markup resembles HTML, but it does have a different set of tags compared it - as can be seen from the example image snippet below:

<amp-img src="welcome.jpg" alt="Welcome" height="400" width="800"></amp-img>

Developers need to write to completely different versions of their templates. Automatic conversions from HTML to AMP are possible, but for optimal experience developers should craft and test AMP markup instead of relying on automatic conversions that degrade user experience.

This of course, requires quite a bit of work and learning the ins and outs of the AMP markup standard. Symfony developers mostly work with the widely used Twig templating language, which is completely agnostic to the output - one can create HTML, XML or even JSON output with Twig. Implementing the AMP component specification is no different.

To aid working with AMP markup in Twig templates, there is a new base theme, AMPTwigTheme, for Twig that implements core AMP elements. The project is built by Beñat Espiña and provides easy access to AMP templates, such as the image example on top:

{% include '@AMP/components/builtins/img.html.twig' with {
    img_src: '/welcome.jpg',
    img_alt: "welcome"
    img_height: 400,
    img_width: 800
} %}

The AMPTwigTheme theme works with Symfony Standard Edition, Flex and other projects using Twig as standalone projects just using Twig as a templating engine. This and other aspects of the usage of the project are covered in the documentation: AMP Twig Theme documentation

If you plan to create AMP templates for your projects, then it is a good idea to take a look at this project and contributing to it rather then reinventing the wheel and building your own Twig AMP snippet library.

Learn more about Accelerated Mobile Pages:


Written by Jani Tarvainen on Sunday December 10, 2017
Permalink -

« Benchmarks: Symfony 3 Standard Edition vs. Symfony 4 Flex - PHP-PM 1.0 launches with Docker images and Symfony 3+ support »