Skip to main content

Django Single File Templates -- inspired by Vue's Single file components

Project description

Django Single File Templates

image

Python 3.x

Django Single File Templates -- inspired by Vue's Single file components

Make your Django templates more organized by holding your HTML and all the related CSS and JavaScript in a sensible way.

example.sft

<template>
{% extends 'example/base.sft' %}}
{% block main %}
    <h1>This is index page</h1>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Fugit eaque obcaecati maxime eos inventore tenetur, debitis atque quaerat modi, et illum id error quisquam consequatur reprehenderit, laboriosam exercitationem, provident aut.</p>

    <h2 id="time"></h2>
{% endblock %}
</template>

<script>
document.getElementById('time').innerHTML = new Date();
</script>

<style>
p {
    width: 50%;
    background-color: white;
    margin: auto;
}
</style>

Disclaimer: This package serves as a proof of concept rather than a production-ready solution!

Motivation

From Vue's documentation:

One important thing to note is that separation of concerns is not equal to separation of file types. In modern UI development, we have found that instead of dividing the codebase into three huge layers that interweave with one another, it makes much more sense to divide them into loosely-coupled components and compose them. Inside a component, its template, logic and styles are inherently coupled, and collocating them actually makes the component more cohesive and maintainable.

Similar logic could be applied to Django's templates. HTML, JavaScript and CSS are inherently coupled so it makes sense to put them together.

Introducing Django Single File Templates (SFT).

Quickstart

Install Django Single File Templates:

pip install django-sft

Add it to your INSTALLED_APPS:

INSTALLED_APPS = (
    ...
    'django_sft',
    ...
)

Add SFT Template loader (in your settings.py):

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'loaders': [
                'django_sft.template.SFTLoader',
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ],
            ...
        }
    }
]

You can now start using Single file templates as your templates.

Usage

Add a new SFT by adding a .sft file to your templates folder (either in your apps or root templates folder). SFT should include at least HTML (you can use Django's template language), but it can also include script and style tags:

<template>
{% load static %}
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Example Website</title>
    </head>
    <body>
        <header>
            <nav>
                <a href="/">Home</a>
                <a href="/page" id="page">Page</a>
            </nav>
        </header>
        {% block main %}
        <h1>This is where the content will go</h1>
        {% endblock %}
    </body>
</html>
</template>
<script>
const page = document.getElementById('page');
page.addEventListener('click', (ev) => {
  ev.preventDefault();
  alert('You clicked the page');
});
</script>

<style>
body {
  background-color: gray;
}
</style>

In your views you can render this template directly and SFT Template loader will get the right template for you.

def view(request):
    return render('my-template.sft')

Single file templates can also extend other STFs.

<template>
{% extends 'example/base.sft' %}}
{% block main %}
    <h1>This is index page</h1>
    <h2>Update</h2>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Fugit eaque obcaecati maxime eos inventore tenetur, debitis atque quaerat modi, et illum id error quisquam consequatur reprehenderit, laboriosam exercitationem, provident aut.</p>

    <h2 id="time"></h2>
{% endblock %}
</template>

<script>
document.getElementById('time').innerHTML = new Date();
</script>

<style>
p {
    width: 50%;
    background-color: white;
    margin: auto;
}
</style>

It can also include external scripts and styles (bootstrap example):

<template>
...
</template>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
const page = document.getElementById('page');
page.addEventListener('click', (ev) => {
  ev.preventDefault();
  alert('You clicked the page');
});
</script>

<style src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"></style>

<style>
body {
  background-color: gray;
}
</style>

Single file templates will automatically be parsed and compiled when you manage.py runserver if DEBUG = True. You can also run manage.py compile_sft to compile manually.

How does it work?

When SFT is compiled (on runserver or manually), django-sft will grab the SFT file and produce appropriate .js, .css and .html files. They will be created in sft directory (under static and templates directories respectively). The html files will be automatically injected with references to the static files. When a view will try to render .sft template, the SFT Template Loader will look for resulting .html file instead and return that.

The current implementation is quite simple and serves as a proof of concept rather than a production-ready solution.

Look for a working example under tests folder.

Features

  • TODO

Running Tests

  • TODO: no tests written yet

Does the code actually work?

source <YOURVIRTUALENV>/bin/activate
(myenv) $ pip install tox
(myenv) $ tox

Credits

Tools used in rendering this package:

History

0.1.2 (2020-11-20) ++++++++++++++++++

  • Enable external scripts and styles
  • Enable multiple scripts and styles per file

0.1.1 (2020-11-16) ++++++++++++++++++

  • Bug fixes

0.1.0 (2020-11-12) ++++++++++++++++++

  • First release on PyPI.

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

django-sft-0.1.2.tar.gz (14.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_sft-0.1.2-py2.py3-none-any.whl (10.7 kB view details)

Uploaded Python 2Python 3

File details

Details for the file django-sft-0.1.2.tar.gz.

File metadata

  • Download URL: django-sft-0.1.2.tar.gz
  • Upload date:
  • Size: 14.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.25.0 setuptools/46.1.3 requests-toolbelt/0.9.1 tqdm/4.52.0 CPython/3.8.1

File hashes

Hashes for django-sft-0.1.2.tar.gz
Algorithm Hash digest
SHA256 50ea64f9ed620b09db17578b41bb1f7470c0ef6b1588b72ff151ddd2d19a5970
MD5 88e319698adee185ed5a9ab65a7daa52
BLAKE2b-256 902660f6f817b8e36455749b12c7eb2612bef9956b324b175796cc458d0db09a

See more details on using hashes here.

File details

Details for the file django_sft-0.1.2-py2.py3-none-any.whl.

File metadata

  • Download URL: django_sft-0.1.2-py2.py3-none-any.whl
  • Upload date:
  • Size: 10.7 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.25.0 setuptools/46.1.3 requests-toolbelt/0.9.1 tqdm/4.52.0 CPython/3.8.1

File hashes

Hashes for django_sft-0.1.2-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 2c8250bf5fab7233bdab7f3ef001aa30f8978f07b5b91dd4b576e04132dbcdef
MD5 d9f37139bef8b17d85095a2cefbf601f
BLAKE2b-256 7c7d8612b4aa4a355b7942c2ea181700f285d3c1df706e35269a2b15ead438fb

See more details on using hashes here.

Supported by

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