2
0

amp.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. How to build a site with AMP support
  2. ====================================
  3. This recipe document describes a method for creating an
  4. `AMP <https://amp.dev/>`_ version of a Wagtail site and hosting it separately
  5. to the rest of the site on a URL prefix. It also describes how to make Wagtail
  6. render images with the ``<amp-img>`` tag when a user is visiting a page on the
  7. AMP version of the site.
  8. Overview
  9. --------
  10. In the next section, we will add a new URL entry that points at Wagtail's
  11. internal ``serve()`` view which will have the effect of rendering the whole
  12. site again under the ``/amp`` prefix.
  13. Then, we will add some utilities that will allow us to track whether the
  14. current request is in the ``/amp`` prefixed version of the site without needing
  15. a request object.
  16. After that, we will add a template context processor to allow us to check from
  17. within templates which version of the site is being rendered.
  18. Then, finally, we will modify the behaviour of the ``{% image %}`` tag to make it
  19. render ``<amp-img>`` tags when rendering the AMP version of the site.
  20. Creating the second page tree
  21. -----------------------------
  22. We can render the whole site at a different prefix by duplicating the Wagtail
  23. URL in the project ``urls.py`` file and giving it a prefix. This must be before
  24. the default URL from Wagtail, or it will try to find ``/amp`` as a page:
  25. .. code-block:: python
  26. # <project>/urls.py
  27. urlpatterns += [
  28. # Add this line just before the default ``include(wagtail_urls)`` line
  29. path('amp/', include(wagtail_urls)),
  30. path('', include(wagtail_urls)),
  31. ]
  32. If you now open ``http://localhost:8000/amp/`` in your browser, you should see
  33. the homepage.
  34. Making pages aware of "AMP mode"
  35. --------------------------------
  36. All the pages will now render under the ``/amp`` prefix, but right now there
  37. isn't any difference between the AMP version and the normal version.
  38. To make changes, we need to add a way to detect which URL was used to render
  39. the page. To do this, we will have to wrap Wagtail's ``serve()`` view and
  40. set a thread-local to indicate to all downstream code that AMP mode is active.
  41. .. note:: Why a thread-local?
  42. (feel free to skip this part if you're not interested)
  43. Modifying the ``request`` object would be the most common way to do this.
  44. However, the image tag rendering is performed in a part of Wagtail that
  45. does not have access to the request.
  46. Thread-locals are global variables that can have a different value for each
  47. running thread. As each thread only handles one request at a time, we can
  48. use it as a way to pass around data that is specific to that request
  49. without having to pass the request object everywhere.
  50. Django uses thread-locals internally to track the currently active language
  51. for the request.
  52. Python implements thread-local data through the ``threading.local`` class,
  53. but as of Django 3.x, multiple requests can be handled in a single thread
  54. and so thread-locals will no longer be unique to a single request. Django
  55. therefore provides ``asgiref.Local`` as a drop-in replacement.
  56. Now let's create that thread-local and some utility functions to interact with it,
  57. save this module as ``amp_utils.py`` in an app in your project:
  58. .. code-block:: python
  59. # <app>/amp_utils.py
  60. from contextlib import contextmanager
  61. from asgiref.local import Local
  62. _amp_mode_active = Local()
  63. @contextmanager
  64. def activate_amp_mode():
  65. """
  66. A context manager used to activate AMP mode
  67. """
  68. _amp_mode_active.value = True
  69. try:
  70. yield
  71. finally:
  72. del _amp_mode_active.value
  73. def amp_mode_active():
  74. """
  75. Returns True if AMP mode is currently active
  76. """
  77. return hasattr(_amp_mode_active, 'value')
  78. This module defines two functions:
  79. - ``activate_amp_mode`` is a context manager which can be invoked using Python's
  80. ``with`` syntax. In the body of the ``with`` statement, AMP mode would be active.
  81. - ``amp_mode_active`` is a function that returns ``True`` when AMP mode is active.
  82. Next, we need to define a view that wraps Wagtail's builtin ``serve`` view and
  83. invokes the ``activate_amp_mode`` context manager:
  84. .. code-block:: python
  85. # <app>/amp_views.py
  86. from django.template.response import SimpleTemplateResponse
  87. from wagtail.core.views import serve as wagtail_serve
  88. from .amp_utils import activate_amp_mode
  89. def serve(request, path):
  90. with activate_amp_mode():
  91. response = wagtail_serve(request, path)
  92. # Render template responses now while AMP mode is still active
  93. if isinstance(response, SimpleTemplateResponse):
  94. response.render()
  95. return response
  96. Then we need to create a ``amp_urls.py`` file in the same app:
  97. .. code-block:: python
  98. # <app>/amp_urls.py
  99. from django.urls import re_path
  100. from wagtail.core.urls import serve_pattern
  101. from . import amp_views
  102. urlpatterns = [
  103. re_path(serve_pattern, amp_views.serve, name='wagtail_amp_serve')
  104. ]
  105. Finally, we need to update the project's main ``urls.py`` to use this new URLs
  106. file for the ``/amp`` prefix:
  107. .. code-block:: python
  108. # <project>/urls.py
  109. from myapp import amp_urls as wagtail_amp_urls
  110. urlpatterns += [
  111. # Change this line to point at your amp_urls instead of Wagtail's urls
  112. path('amp/', include(wagtail_amp_urls)),
  113. re_path(r'', include(wagtail_urls)),
  114. ]
  115. After this, there shouldn't be any noticeable difference to the AMP version of
  116. the site.
  117. Write a template context processor so that AMP state can be checked in templates
  118. --------------------------------------------------------------------------------
  119. This is optional, but worth doing so we can confirm that everything is working
  120. so far.
  121. Add a ``amp_context_processors.py`` file into your app that contains the
  122. following:
  123. .. code-block:: python
  124. # <app>/amp_context_processors.py
  125. from .amp_utils import amp_mode_active
  126. def amp(request):
  127. return {
  128. 'amp_mode_active': amp_mode_active(),
  129. }
  130. Now add the path to this context processor to the
  131. ``['OPTIONS']['context_processors']`` key of the ``TEMPLATES`` setting:
  132. .. code-block:: python
  133. # Either <project>/settings.py or <project>/settings/base.py
  134. TEMPLATES = [
  135. {
  136. ...
  137. 'OPTIONS': {
  138. 'context_processors': [
  139. ...
  140. # Add this after other context processors
  141. 'myapp.amp_context_processors.amp',
  142. ],
  143. },
  144. },
  145. ]
  146. You should now be able to use the ``amp_mode_active`` variable in templates.
  147. For example:
  148. .. code-block:: html+Django
  149. {% if amp_mode_active %}
  150. AMP MODE IS ACTIVE!
  151. {% endif %}
  152. Using a different page template when AMP mode is active
  153. -------------------------------------------------------
  154. You're probably not going to want to use the same templates on the AMP site as
  155. you do on the normal web site. Let's add some logic in to make Wagtail use a
  156. separate template whenever a page is served with AMP enabled.
  157. We can use a mixin, which allows us to re-use the logic on different page types.
  158. Add the following to the bottom of the amp_utils.py file that you created earlier:
  159. .. code-block:: python
  160. # <app>/amp_utils.py
  161. import os.path
  162. ...
  163. class PageAMPTemplateMixin:
  164. @property
  165. def amp_template(self):
  166. # Get the default template name and insert `_amp` before the extension
  167. name, ext = os.path.splitext(self.template)
  168. return name + '_amp' + ext
  169. def get_template(self, request):
  170. if amp_mode_active():
  171. return self.amp_template
  172. return super().get_template(request)
  173. Now add this mixin to any page model, for example:
  174. .. code-block:: python
  175. # <app>/models.py
  176. from .amp_utils import PageAMPTemplateMixin
  177. class MyPageModel(PageAMPTemplateMixin, Page):
  178. ...
  179. When AMP mode is active, the template at ``app_label/mypagemodel_amp.html``
  180. will be used instead of the default one.
  181. If you have a different naming convention, you can override the
  182. ``amp_template`` attribute on the model. For example:
  183. .. code-block:: python
  184. # <app>/models.py
  185. from .amp_utils import PageAMPTemplateMixin
  186. class MyPageModel(PageAMPTemplateMixin, Page):
  187. amp_template = 'my_custom_amp_template.html'
  188. Overriding the ``{% image %}`` tag to output ``<amp-img>`` tags
  189. ---------------------------------------------------------------
  190. Finally, let's change Wagtail's ``{% image %}`` tag, so it renders an ``<amp-img>``
  191. tags when rendering pages with AMP enabled. We'll make the change on the
  192. `Rendition` model itself so it applies to both images rendered with the
  193. ``{% image %}`` tag and images rendered in rich text fields as well.
  194. Doing this with a :ref:`Custom image model <custom_image_model>` is easier, as
  195. you can override the ``img_tag`` method on your custom ``Rendition`` model to
  196. return a different tag.
  197. For example:
  198. .. code-block:: python
  199. from django.forms.utils import flatatt
  200. from django.utils.safestring import mark_safe
  201. from wagtail.images.models import AbstractRendition
  202. ...
  203. class CustomRendition(AbstractRendition):
  204. def img_tag(self, extra_attributes):
  205. attrs = self.attrs_dict.copy()
  206. attrs.update(extra_attributes)
  207. if amp_mode_active():
  208. return mark_safe('<amp-img{}>'.format(flatatt(attrs)))
  209. else:
  210. return mark_safe('<img{}>'.format(flatatt(attrs)))
  211. ...
  212. Without a custom image model, you will have to monkey-patch the builtin
  213. ``Rendition`` model.
  214. Add this anywhere in your project where it would be imported on start:
  215. .. code-block:: python
  216. from django.forms.utils import flatatt
  217. from django.utils.safestring import mark_safe
  218. from wagtail.images.models import Rendition
  219. def img_tag(rendition, extra_attributes={}):
  220. """
  221. Replacement implementation for Rendition.img_tag
  222. When AMP mode is on, this returns an <amp-img> tag instead of an <img> tag
  223. """
  224. attrs = rendition.attrs_dict.copy()
  225. attrs.update(extra_attributes)
  226. if amp_mode_active():
  227. return mark_safe('<amp-img{}>'.format(flatatt(attrs)))
  228. else:
  229. return mark_safe('<img{}>'.format(flatatt(attrs)))
  230. Rendition.img_tag = img_tag