Search code examples
pythonjinja2aiohttp

How to employ cache busting with aiohtttp and jinja2?


The documentation for aiohttp states:

When you want to enable cache busting, parameter append_version can be set to True

web.static('/prefix', path_to_static_folder, append_version=True)

(from here)

My question is, how do I inject the version query into the resulting HTML?

For e.g. I have:

<img class="logo" src="/path_to/static/images/logo.png">

in the jinja main layout template.

In the resulting HTML, I want:

<img class="logo" src="/path_to/static/images/logo.png?v=some-hash-value">

but as yet, perhaps not surprisingly, the src remains the same.


Solution

  • The way I've found is to use aiohttp-jinja2. Many thanks to Dreamsorcerer there for putting me on the right road.

    import aiohttp_jinja2
    
    app = web.Application()
    aiohttp_jinja2.setup(
        app,
        loader=jinja2.FileSystemLoader(Path(__file__).parent / "templates"),
    )
    
    app.add_routes(
        [
            web.static(
                "/static",
                Path(__file__).parent / "static",
                name="static",
                append_version=True,
            ),
        ]
    )
    

    in the app setup, and then to use that named static route in a template via the url() global

     <link rel="stylesheet" href="{{ url('static', filename='stylesheets/main.css') }}">