惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

大猫的无限游戏
大猫的无限游戏
MyScale Blog
MyScale Blog
雷峰网
雷峰网
量子位
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 叶小钗
T
Tailwind CSS Blog
月光博客
月光博客
博客园 - 【当耐特】
博客园_首页
罗磊的独立博客
博客园 - 三生石上(FineUI控件)
IT之家
IT之家
爱范儿
爱范儿
阮一峰的网络日志
阮一峰的网络日志
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
WordPress大学
WordPress大学
The Cloudflare Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
S
SegmentFault 最新的问题
人人都是产品经理
人人都是产品经理
V
V2EX
酷 壳 – CoolShell
酷 壳 – CoolShell

alexwlchan’s notes

What is WS11 1DB? Blocking referrers with Caddy How to type a Spanish question mark (¿) on a Mac Non-overlapping type comparisons and Python type checkers Why does t.Setenv panic after t.Parallel? Use Path.glob() and Path.rglob() for typed versions of glob.glob() Curious clocks and colourful eyes Archeologists distinguish between “sherds” and “shards” A single command to test all my changed Go packages Disable the new message animations in WhatsApp Finding high-churn folders that bother Backblaze Always-on SSH agent forwarding with my Git pushes Managing the caption of a photo with AppleScript (but not PhotoKit) Goodhart’s and Campbell’s Law are different Notes from The Cornishman No. 176 (Spring 2026) Notes from The Cornishman No. 176 (Spring 2026) GitUp can’t diff text files larger than 8MB Home Testing the width of a page on a mobile device using Playwright Disable AirPods charging notifications Start a Caddy server in a subprocess during a Python session Filter a list of JSON object based on a list of tags HOME_GET_ME_HOME is a Citymapper Shortcuts action The FileExistsError exception exposes a filename attribute The red-lined bubble snail Why can’t Python connect to example.com? Useful type hints for Python How to truncate the middle of long command output AirPlay Receiver can interfere with Flask apps What’s the main prefix in SQLite queries?
Track which templates are used by Jinja2
2026-08-10 · via alexwlchan’s notes

Override the get_template method on the Environment and see which templates are summoned.

I write my own static site generator, and I do incremental rebuilds when a source file changes. Currently I rebuild the entire website whenever a template changes, which is a lot of redundant work.

I thought it might be useful to track which templates are used by each page, and only rebuild a page if it uses the changed template. I use Jinja for templating, and I wrote this script to work out where I should intercept template calls:

from jinja2 import DictLoader, Environment


class PrintingDictLoader(DictLoader):
    def get_source(self, env: Environment, template: str):
        print(f"Loader.get_source({template!r})")
        return super().get_source(env, template)


class PrintingEnvironment(Environment):
    def get_template(self, name: str, *args, **kwargs):
        print(f"Environment.get_template({name!r})")
        return super().get_template(name, *args, **kwargs)


if __name__ == "__main__":
    loader = PrintingDictLoader(
        {
            "base.html": (
                "This is the base template"
                "{% block content %}{% endblock %}"
            ),
            "article.html": (
                '{% extends "base.html" %}'
                "{% block content %}"
                "This is article {{ title }}"
                "{% endblock %}"
            ),
        }
    )
    env = PrintingEnvironment(loader=loader)

    env.get_template("article.html").render(title="My first article")
    print("---")
    env.get_template("article.html").render(title="My second article")

Here’s the output. We can see the get_template method is called on both renders, but the loader method is only called once because the loaded template gets cached:

$ python3 print_templates.py
Environment.get_template('article.html')
Loader.get_source('article.html')
Environment.get_template('base.html')
Loader.get_source('base.html')
---
Environment.get_template('article.html')
Environment.get_template('base.html')

I’m not pursuing this for now, because my template code is complicated enough already and I need to simplify it a bit before adding more complexity. (Also, I spend less and less time editing templates, so I don’t feel the effect as much.)

I’m writing this note in case I revisit this idea later.