Skip to main content

django-despacer

A lightweight loader for the Django Template Language (DTL) that enables removing excess whitespace by using delimiters like {#- and -#}. It's lightweight because it adds just two regular expressions at template loading time and nothing to request handling time.

This package is intended as a demonstration of this feature. I'm hoping this feature will eventually be included in Django's core code, at which time this package will no longer be needed.

About

I'm a frugal pragmatic perfectionist (with deadlines).

As a perfectionist, I'm horrified by the HTML generated by DTL: so many empty lines and bits of text floating in space. Being pragmatic, I accept that perfect whitespace control that generates perfectly indented HTML is unrealistic; so I'll settle for merely better looking HTML. Being frugal, I won't repeatedly pay a price for it but I'm willing to pay just once (at template load time).

So, I created django-despacer, a Python package which meets these criteria.

Features:

  • At request handling time, it does nothing (no overhead added).
  • At template loading time, just two regular expressions are run to alter templates before they're passed to the template compiler.
    • When DEBUG is False (production), whitespace is removed as indicated by despacing indicators ({#-, -#}, {{-, -}}, {%-, -%}) that you add where you desire.
    • When DEBUG is True (development), only the despacing indicator - is removed. Whitespace is not removed so that DTL compiler error messages have the correct line numbers.
  • Just two regular expressions are added. It's lightweight.
  • My favourite feature: I can now add lots of comments (comments are a good thing), {#- yada yada -#}, without adding lots of blank lines to the HTML generated.

Function

Below ··· represents one or more consecutive space, tab, and new line characters.

  • When DEBUG is False (prod), when a DTL template is loaded:
    • ···{#-, -#}··· are replace with {#, #} respectively.
    • ···{%-, -%}··· are replace with {%, %} respectively.
    • ···{{-, -}}··· are replace with {{, }} respectively.
    • thereby removing blank lines and floating text in the generated HTML.
  • When DEBUG is True (dev), when a DTL template is loaded:
    • ··· is not removed; only the -. Why? The line numbers of the original DTL source code must match the line numbers in the compiler's input to have correct line numbers in any error messages. That's important in development.
    • {#-, -#} are replace with {#, #} respectively.
    • {%-, -%} are replace with {%, %} respectively.
    • {{-, -}} are replace with {{, }} respectively.

Usage

In my DTL templates I usually:

  • Despace before and after comments {#- yada yada -#}. I can now have many lines of comments without having many empty lines in my generated HTML!
  • Despace before but not after tags like {%- if ... %}. This omits the empty line but still has a new-line after. See if below.
  • Despace before and after when I want to squeeze things down more. See <button> below where I want a one-liner.
<div>
  {#- I can now add lots of comments to my template -#}
  {#- ... without adding a ton of empty lines! -#}
  {#- the {%- on the `if` below removes empty lines -#}
  {#- I added for readability -#}

  {%- if not user.is_authenticated %}
    Howdy, stranger!
  {%- else %}
    Welcome back, {{ user.name }}.
  {%- endif -%}

  <button>
    {#- Despacing before and after collapses <button> down to a one liner -#}
    {%- translate "Save and Publish" -%}
    {#- Isn't it just great to be able to add lots of comments! -#}
  </button>
</div>

Without django-despacer (and without the -), the HTML would look like:

<div>
  
  




    Howdy, stranger!
  


  <button>
    
    Save and Publish
    
  </button>
</div>

... but with django-despacer:

<div>
    Howdy, stranger!
  <button>Save and Publish</button>
</div>

Installation

  • Requirements:

    • Python >= 3.4
    • Django >= 2.0
  • Install the package: uv add django-despacer (or for old-schoolers pip install django-despacer)

  • Configure Django settings to use the template loader provided

TEMPLATES = [
  {
    # ...
    "OPTIONS": {
      # ...
      "loaders": [
        (
          "django_despacer.DespacingLoader",
          [
            (
              "django.template.loaders.cached.Loader",
              [
                "django.template.loaders.filesystem.Loader",
                "django.template.loaders.app_directories.Loader",
              ]
            )
          ],
        ),
      ],
    },
  },
]
  • You must wrap all your other template loaders with DespacingLoader.
  • Since you are explicitly listing your loaders, don't forgot important ones that are magically added for you, such as cached.Loader, when "loaders" is not configured.
  • Apologies for the ugly configuration. If Django adopts this feature into core, you'll just need to remove the loader. All your templates won't need modifying.

License

This project is licensed under the MIT License.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_despacer-0.1.1.tar.gz (4.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_despacer-0.1.1-py3-none-any.whl (4.6 kB view details)

Uploaded Python 3

File details

Details for the file django_despacer-0.1.1.tar.gz.

File metadata

  • Download URL: django_despacer-0.1.1.tar.gz
  • Upload date:
  • Size: 4.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.31 {"installer":{"name":"uv","version":"0.11.31","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for django_despacer-0.1.1.tar.gz
Algorithm Hash digest
SHA256 fbaae027a5b5f14426fed40efeb3585fa91ed01e55e5d245ab386789e63524d4
MD5 6527d4259348b23ad05f27f5852f2aff
BLAKE2b-256 b7b68b52d7df5a15b23be0b7885dda823598e4a9d693a7adc02faaa9cdf856e1

See more details on using hashes here.

File details

Details for the file django_despacer-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: django_despacer-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 4.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.31 {"installer":{"name":"uv","version":"0.11.31","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for django_despacer-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b95a28a763b1d33bcfd552beab5f35fc5d9e5b95f8a4cb39e084d6f055c055d7
MD5 9809445f46ae6400da1707c112c92e16
BLAKE2b-256 3bd3b1bc1f1a8cda429a8cf692406b5c4062b7c6b6829685db7b9e1ec0866178

See more details on using hashes here.

Release history Release notifications | RSS feed

0.1.4

2 files

0.1.3

2 files

0.1.2

2 files

This release

0.1.1 This release

2 files

0.1.0

2 files

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page