Skip to main content

canonicalwebteam.image-template

PyPI Tests Code coverage

A module to generate performant HTML image markup for images. The markup will:

  • Use native lazyloading
  • Explicitly define width and height attributes to avoid the page jumping effect
  • Prefix all image URLs with cloudinary CDN proxy URLs, to transform the image to the optimal size
  • Use predefined (2x) srcset break points for hidef screens

Parameters

  • url (mandatory string): The url to an image (e.g. https://assets.ubuntu.com/v1/9f6916dd-k8s-prometheus-light.png)
  • alt (mandatory string): Alt text to describe the image
  • hi_def (mandatory boolean): Has an image been uploaded 2x the width and height of the desired size
  • width (mandatory integer): The number of pixels wide the image should be
  • height (optional integer): The number of pixels high the image should be
  • fill (optional boolean): Set the crop mode to "fill"
  • loading (optional string, default: "lazy"): Set to "auto" or "eager" to disable lazyloading
  • fmt (optional string, default: "auto"): Define the file format (e.g. fmt="jpg")
  • bypass_cloudinary (optional boolean, default: False): Serve the url as-is instead of proxying through Cloudinary (e.g. for animated images, since Cloudinary truncates animations it transforms on the fly to 100 frames). All transformation parameters are ignored eg. hi_def, fill, e_sharpen
  • attrs (optional dictionary): Extra <img> attributes (e.g. class or id) can be passed as additional arguments
  • output_mode (optional string, default: "html"): The output mode can be set to either html or attrs. If set to attrs, the function will return an object with the image attributes instead of HTML markup.

Usage

Local development

For local development, it's best to test this module with one of our website projects like ubuntu.com. For more information, follow this guide (internal only).

Application code

The image_template function can be used directly to generate image Markup.

from canonicalwebteam import image_template

image_markup = image_template(
    url="https://assets.ubuntu.com/v1/450d7c2f-openstack-hero.svg",
    alt="",
    width="534",
    height="319",
    hi_def=True,
    loading="auto",
	fill=True,
    attrs={"class": "hero", "id": "openstack-hero"},
)

However, the most common usage is to add it to Django or Flask template contexts, as an image function.

Django usage

Add it as a template tag:

# myapp/templatetags.py

from canonicalwebteam import image_template
from django import template
from django.utils.safestring import mark_safe


register = template.Library()

@register.simple_tag
def image(*args, **kwargs):
    return mark_safe(image_template(*args, **kwargs))


# settings.py

TEMPLATES[0]["OPTIONS"]["builtins"].append("myapp.templatetags")

Use it in templates:

# templates/mytemplate.html

{% image url="https://assets.ubuntu.com/v1/9f6916dd-k8s-prometheus-light.png" alt="Operational dashboard" width="1040" height="585" hi_def=True fill=True %}

Flask usage

Add it as a template tag:

# app.py

from canonicalwebteam import image_template
from flask import Flask

app = Flask(__name__)

@app.context_processor
def utility_processor():
    return {"image": image_template}

Use it in templates, e.g.::

# templates/mytemplate.html

{{
  image(
    url="https://assets.ubuntu.com/v1/450d7c2f-openstack-hero.svg",
    alt="",
    width="534",
    height="319",
    hi_def=True,
	fill=True,
    loading="auto",
    attrs={"class": "hero", "id": "openstack-hero"},
  ) | safe
}}

Generated markup

The output image markup will be e.g.:

<img
    src="https://res.cloudinary.com/canonical/image/fetch/f_auto,q_auto,fl_sanitize,w_534,h_319,c_fill/https://assets.ubuntu.com/v1/450d7c2f-openstack-hero.svg"
    srcset="https://res.cloudinary.com/canonical/image/fetch/f_auto,q_auto,fl_sanitize,w_1068,h_638,c_fill/https://assets.ubuntu.com/v1/450d7c2f-openstack-hero.svg 2x"
    alt=""
    width="534"
    height="319"
    loading="auto"
    class="hero"
    id="openstack hero"
/>

Attribute output

In some cases, you may want to use the image attributes generated by this utility, rather than directly rendering its markup. This allows you to add the image attributes to an existing <img> tag, or to use them in a different context. To do this, you can set the output_mode parameter to attrs when calling the image_template function.

For example, some Vanilla patterns may require image attributes to be passed as a dictionary, in order to allow the pattern itself to construct the image element.

{%-
  call(slot) vf_tiered_list(
    # other params...
    img_attrs=image(
    url="https://assets.ubuntu.com/v1/3f63a18c-data-center.png",
    alt="",
    width="2464",
    height="1028",
    hi_def=True,
    loading="auto",
    attrs={"class": "my-class-name"},
    output_mode="attrs"
  )
) -%}

Result:

{
  'src': 'https://res.cloudinary.com/canonical/image/fetch/f_auto,q_auto,fl_sanitize,w_2464,h_1028/https://assets.ubuntu.com/v1/3f63a18c-data-center.png', 
  'srcset': 'https://res.cloudinary.com/canonical/image/fetch/c_limit,f_auto,q_auto,fl_sanitize,w_4928,h_2056/https://assets.ubuntu.com/v1/3f63a18c-data-center.png 2x', 
  'class': 'my-class-name',
  'alt': '', 
  'width': 2464, 
  'height': '1028', 
  'hi_def': True, 
  'loading': 'auto'
} 

VS Code Snippet

To add the required markup for this template as a User Snippet, add the following as a HTML snippet (User Snippets under File > Preferences, or Code > Preferences on macOS):

"Image module": {
	"prefix": "image-module",
	"body": [
		"{{",
		"	image_template(",
		"		url=\"$1\",",
		"		alt=\"$2\",",
		"		height=\"$3\",",
		"		width=\"$4\",",
		"		hi_def=$5True,",
		"		loading=\"auto|lazy$6\",",
		"		attrs={\"class\": \"$7\"}",
		"	) | safe",
		"}}"
	],
	"description": "Image module include"
}"

Metadata

Release files for canonicalwebteam.image-template 1.10.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for canonicalwebteam.image-template 1.10.0
File Size Uploaded
canonicalwebteam_image_template-1.10.0.tar.gz 8.8 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for canonicalwebteam.image-template 1.10.0
File Interpreter ABI Platform
canonicalwebteam_image_template-1.10.0-py3-none-any.whl Python 3 none any Details

Total release size: 15.7 kB

Release files / canonicalwebteam_image_template-1.10.0.tar.gz

Download URL canonicalwebteam_image_template-1.10.0.tar.gz
Size 8.8 kB
Tags Source
SHA-256 checksum
How to use checksums
3bd4d3cd5c172c7b6930e40d283a5913878f612dafd963c5a8a73986ff33ac86
BLAKE2b-256 checksum
How to use checksums
e7a428eb9f3fc1d1cb5f3c818e6c078fecda2c9f2c508f012af3f7702a61fc15
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.25

Release files / canonicalwebteam_image_template-1.10.0-py3-none-any.whl

Download URL canonicalwebteam_image_template-1.10.0-py3-none-any.whl
Size 6.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5760a4f5366c4f2ea49c93cfba94e15ed3926bb1fc85794cd7edd13bf43095f9
BLAKE2b-256 checksum
How to use checksums
cc9537fd29d248cb57259db626fbdfe1d28a09a222d01fa30005174bae0b3e30
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.25
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page