Skip to main content

Adds more bracket angles to Django templates </>

Project description

dj-angles </>

Adds more bracket angles to Django templates

PyPI PyPI - Downloads GitHub Sponsors

This code is experimental -- use with caution! Or maybe not at all! 🤷

📦 Package located at https://pypi.org/project/dj-angles/.

⭐ Features

  • Use HTML-like elements in Django templates, e.g. <dj-partial /> instead of {% include 'partial.html' %}
  • Can be sprinkled in as needed, but does not remove existing Django functionality
  • Pretend like you are writing React components, but without dealing with JavaScript at all
  • Lets you excitedly tell your friends how neat the Shadow DOM is
  • Since it looks like HTML, syntax highlighting mostly "just works"

⚡ Installation

  1. Create a new Django project or cd to an existing project
  2. pip install dj-angles to install the dj-angles package
  3. Edit settings.py TEMPLATES and add "dj_angles.template_loader.Loader", as the first loader. Note: you might need to add the "loaders" key since it is not there by default: https://docs.djangoproject.com/en/stable/ref/templates/api/#django.template.loaders.cached.Loader.
TEMPLATES = [
  "BACKEND": "django.template.backends.django.DjangoTemplates",
  # "APP_DIRS": True,  # this cannot be specified if loaders are explicitly set
  "DIRS": [],
  "OPTIONS": {
      "builtins": builtins,
      "context_processors": [
          "django.template.context_processors.request",
          "django.template.context_processors.debug",
          "django.template.context_processors.static",
      ],
      "loaders": [
          (
              "django.template.loaders.cached.Loader",
              [
                  "dj_angles.template_loader.Loader",  # this is required for `dj-angles`
                  "django.template.loaders.filesystem.Loader",
                  "django.template.loaders.app_directories.Loader",
              ],
          )
      ],
  },
]

✨ Inspiration

I have been interested in Django components and encapsulating functionality for a long time (see django-unicorn, dlitejs, etc), but had never thought of using HTML directly until I looked at Cotton by wrabit.

💡

Since <c-component /> is a high-powered wrapper around {% include %}, what if other Django templatetags could also be wrapped? This library is an experiment to see what that experience is like and how well it works.

🤔 How does this work?

Basically, Django template loaders are super powerful. The raw template content is passed through dj_angles.template_loader.Loader first, some transformations happen (via good ole' regex), and then the normal template loaders process the output like normal.

💥 Template example

base.html

<dj-block 'content'>
</dj-block 'content'>

index.html

<dj-extends 'base.html' />  <!-- {% extends 'base.html' %} -->

<dj-block 'content'>  <!-- {% block 'content' %} -->
  <dj-include 'partial.html' />  <!-- {% include 'partial.html' %} -->

  <dj-verbatim>  <!-- {% verbatim %} -->
    This is verbatim: {% include %}
  </dj-verbatim>  <!-- {% endverbatim %} -->

  <dj-comment>  <!-- {% comment %} -->
    this is a comment
  </dj-comment>  <!-- {% endcomment %} -->

  <dj-#>this is another comment</dj-#>    <!-- {# this is another comment #} -->

  <dj-autoescape-on>  <!-- {% autoescape-on %} -->
    This is escaped
  </dj-autoescape-on>  <!-- {% endautoescape %} -->

  <dj-autoescape-off>  <!-- {% autoescape off %} -->
    This is not escaped
  </dj-autoescape-off>  <!-- {% endautoescape %} -->

  <dj-csrf />  <!-- {% csrf_token %} -->
  
  <dj-debug />  <!-- {% debug %} -->
</dj-block 'content'>  <!-- {% endblock 'content' %} -->

partial.html

<div style="border: 1px solid red;">
  <p>
    This is a partial: {{ now|date:"c" }}
  </p>
</div>

<style>
  p {
    color: green;
  }
</style>

🪄 Include tags

These are equivalent ways to include partial HTML files.

<dj-include 'partial.html' />
<dj-partial />

They both compile to the following Django template syntax.

{% include 'partial.html' %}
The [other tags](#️-other-tags) are considered reserved words. Template file names that conflict with the those words won't get loaded because reserved words take precedence.

Those templates would need to use `<dj-include 'partial.html' />` to include the template.

⤵️ Directories

Accessing templates in directories is supported even though technically forward-slashes aren't permitted in a custom element. It will definitely confound most HTML syntax highlighters.

<dj-include 'directory/partial.html' />
<dj-directory/partial />

🥷 CSS scoping

To encapsulate component styles, enable the Shadow DOM for the partial. This will ensure that any style element in the partial will be contained to that partial. The downside is that the Shadow DOM does not allow outside styles in, other than CSS variables.

These are all equivalent ways to include partials.

<dj-include 'partial.html' shadow />
<dj-partial shadow />
<dj-partial! />

They all compile to the following Django template syntax.

<template shadowrootmode='open'>{% include 'partial.html' %}</template>

🛠️ Other tags

#

<dj-#>...</dj-#>
{# ... #}

autoescape-off

<dj-autoescape-off>
  ...
</dj-autoescape-off>
{% autoescape off %}
{% endautoescape %}

autoescape-on

<dj-autoescape-on>
  ...
</dj-autoescape-on>
{% autoescape on %}
{% endautoescape %}

block

<dj-block 'content'>
  ...
</dj-block 'content'>
{% block 'content' %}
  ...
{% endblock 'content' %}

csrf, csrf-token, csrf-input

<dj-csrf />
{% csrf_token %}

comment

<dj-comment>
  ...
</dj-comment>
{% comment %}
  ...
{% endcomment %}

debug

<dj-debug />
{% debug %}

extends

<dj-extends 'base.html' />
{% extends 'base.html' %}

filter

<dj-filter ... />
{% filter ... %}

lorem

<dj-lorem />
{% lorem %}

now

<dj-now />
{% now %}

spaceless

<dj-spaceless>
  ...
</dj-spaceless>
{% spaceless %}
  ...
{% endspaceless %}

templatetag

<dj-templatetag ... />
{% templatetag ... %}

verbatim

<dj-verbatim>
  ...
</dj-verbatim>
{% verbatim %}
  ...
{% endverbatim %}

Settings

Settings can be configured via an ANGLES dictionary in settings.py.

ANGLES = {}

initial_tag_regex

Determines the characters that are used to indicate a dj-angles element. String which defaults to r"(dj-)".

Special character

ANGLES = {
  "initial_tag_regex": r"(dj-|\$)"
}
<dj-partial />
<$partial />
{% include 'partial.html' %}

Regular element

ANGLES = {
  "initial_tag_regex": ""
}
<partial />
{% include 'partial.html' %}

React-like component

ANGLES = {
  "initial_tag_regex": "",
  "lower_case_tag": True
}
<Partial />
{% include 'partial.html' %}

lower_case_tag

Lower-cases the tag. Boolean which defaults to False.

mappers

Provide additional mappers. Dictionary which defaults to {}.

The key is always a string and is the regex match after the initial_tag_regex, i.e. for the default initial_tag_regex of r"(dj-)", the key would match after "dj-" until a space or a >.

string value

When the dictionary value is a string, it replaces the initial_tag_regex + the key, and puts it into a template tag.

# settings.py

ANGLES = {
    "mappers": {
        "blob": "include",
    },
}
<dj-blob 'partial.html' />
{% include 'partial.html' %}

Callable

When the dictionary value is a callable, the output can be completely controlled.

# settings.py

def map_blob(component_name, template_tag_args, is_tag_closing):
    return "blob2"

ANGLES = {
    "mappers": {
        "blob": map_blob,
    },
}
<dj-blob />
blob2

Project details


Download files

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

Source Distribution

dj_angles-0.2.0.tar.gz (16.9 kB view details)

Uploaded Source

Built Distribution

dj_angles-0.2.0-py3-none-any.whl (9.0 kB view details)

Uploaded Python 3

File details

Details for the file dj_angles-0.2.0.tar.gz.

File metadata

  • Download URL: dj_angles-0.2.0.tar.gz
  • Upload date:
  • Size: 16.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.9.7

File hashes

Hashes for dj_angles-0.2.0.tar.gz
Algorithm Hash digest
SHA256 90c6e0730d8c8b29e7e7ac6756d54346d5c27582fb09a3fdf249f6acede45082
MD5 e8e48a60c6a2612470deb023597955a7
BLAKE2b-256 9e7e223121aa7a99a20891592e49f3993f9e0d03508559a88f2f4c21a8a2e85f

See more details on using hashes here.

File details

Details for the file dj_angles-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: dj_angles-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 9.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.9.7

File hashes

Hashes for dj_angles-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ed26841031d055905103eb79b311a970d069c63e4d2134ee54fe7147fd0321de
MD5 1fbe5e9ed9edc8ea27cbd41e1e3a5af7
BLAKE2b-256 1444c6594b4cd52f6caab55aede9eefdc28ade0671b31d73178114bf04597a6e

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page