mirror of
https://github.com/django-components/django-components.git
synced 2025-08-04 06:18:17 +00:00
chore: init docs
This commit is contained in:
parent
899b9a2738
commit
163b0941c2
49 changed files with 1447 additions and 9 deletions
20
.github/workflows/docs.yml
vendored
Normal file
20
.github/workflows/docs.yml
vendored
Normal file
|
@ -0,0 +1,20 @@
|
|||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
# XXX Commented-out for testing
|
||||
# branches:
|
||||
# - main
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-python@v5
|
||||
- run: pip install -r requirements-docs.txt
|
||||
- name: Publish Dev Docs
|
||||
run: |
|
||||
git config user.name github-actions
|
||||
git config user.email github-actions@github.com
|
||||
mike deploy --push dev
|
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -72,3 +72,4 @@ poetry.lock
|
|||
.venv/
|
||||
.DS_Store
|
||||
.python-version
|
||||
site
|
||||
|
|
32
README.md
32
README.md
|
@ -3,9 +3,29 @@
|
|||
<a href="https://github.com/EmilStenstrom/django-components/actions?query=workflow%3A%22Run+tests%22"><img align="right" src="https://github.com/EmilStenstrom/django-components/workflows/Run%20tests/badge.svg" alt="Show test status"></a>
|
||||
<a href="https://pepy.tech/project/django-components"><img align="right" src="https://pepy.tech/badge/django-components" alt="Show download stats"></a>
|
||||
|
||||
A way to create simple reusable template components in Django.
|
||||
[](https://pypi.org/project/django-components/) [](https://pypi.org/project/django-components/) [](https://EmilStenstrom.github.io/django-components/latest/license/) [](https://pypistats.org/packages/django-components) [](https://github.com/EmilStenstrom/django-components/actions/workflows/tests.yml)
|
||||
|
||||
It lets you create "template components", that contains both the template, the Javascript and the CSS needed to generate the front end code you need for a modern app. Components look like this:
|
||||
[**Docs**](https://EmilStenstrom.github.io/django-components/latest/)
|
||||
|
||||
|
||||
Create simple reusable template components in Django
|
||||
|
||||
|
||||
## Features
|
||||
|
||||
<!-- FIXME Links -->
|
||||
|
||||
- ✨ **Reusable components**: Create components that can be reused in different parts of your project, or even in different projects.
|
||||
- 📁 **Single file components**: Keep your Python, CSS, Javascript and HTML in one place (if you wish)
|
||||
- 🎰 **Slots**: Define slots in your components to make them more flexible.
|
||||
- 💻 **CLI**: A command line interface to help you create new components.
|
||||
- 🚀 **Wide compatibility**: Works with [modern and LTS versions of Django](/user_guide/compatibility).
|
||||
- **Load assets**: Automatically load the right CSS and Javascript files for your components, with [our middleware](/user_guide/middleware).
|
||||
|
||||
|
||||
## Summary
|
||||
|
||||
It lets you create "template components", that contains both the template, the Javascript and the CSS needed to generate the front end code you need for a modern app. Use components like this:
|
||||
|
||||
```htmldjango
|
||||
{% component "calendar" date="2015-06-19" %}{% endcomponent %}
|
||||
|
@ -49,7 +69,7 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
|
|||
|
||||
## Release notes
|
||||
|
||||
🚨📢 **Version 0.92**
|
||||
🚨📢 **Version 0.92**
|
||||
- BREAKING CHANGE: `Component` class is no longer a subclass of `View`. To configure the `View` class, set the `Component.View` nested class. HTTP methods like `get` or `post` can still be defined directly on `Component` class, and `Component.as_view()` internally calls `Component.View.as_view()`. (See [Modifying the View class](#modifying-the-view-class))
|
||||
|
||||
- The inputs (args, kwargs, slots, context, ...) that you pass to `Component.render()` can be accessed from within `get_context_data`, `get_template_string` and `get_template_name` via `self.input`. (See [Accessing data passed to the component](#accessing-data-passed-to-the-component))
|
||||
|
@ -121,7 +141,7 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
|
|||
|
||||
🚨📢 **Version 0.5** CHANGES THE SYNTAX for components. `component_block` is now `component`, and `component` blocks need an ending `endcomponent` tag. The new `python manage.py upgradecomponent` command can be used to upgrade a directory (use --path argument to point to each dir) of templates that use components to the new syntax automatically.
|
||||
|
||||
This change is done to simplify the API in anticipation of a 1.0 release of django_components. After 1.0 we intend to be stricter with big changes like this in point releases.
|
||||
## Getting started
|
||||
|
||||
**Version 0.34** adds components as views, which allows you to handle requests and render responses from within a component. See the [documentation](#use-components-as-views) for more details.
|
||||
|
||||
|
@ -598,7 +618,7 @@ MyComponent.render_to_response(
|
|||
### Adding type hints with Generics
|
||||
|
||||
The `Component` class optionally accepts type parameters
|
||||
that allow you to specify the types of args, kwargs, slots, and
|
||||
that allow you to specify the types of args, kwargs, slots, and
|
||||
data.
|
||||
|
||||
```py
|
||||
|
@ -786,7 +806,7 @@ class ComponentView(View):
|
|||
|
||||
def post(self, request, *args, **kwargs):
|
||||
return self.component.post(request, *args, **kwargs)
|
||||
|
||||
|
||||
...
|
||||
```
|
||||
|
||||
|
|
17
docs/CHANGELOG.md
Normal file
17
docs/CHANGELOG.md
Normal file
|
@ -0,0 +1,17 @@
|
|||
# Release notes
|
||||
|
||||
🚨📢 **Version 0.5** CHANGES THE SYNTAX for components. `component_block` is now `component`, and `component` blocks need an ending `endcomponent` tag. The new `python manage.py upgradecomponent` command can be used to upgrade a directory (use --path argument to point to each dir) of components to the new syntax automatically.
|
||||
|
||||
This change is done to simplify the API in anticipation of a 1.0 release of django_components. After 1.0 we intend to be stricter with big changes like this in point releases.
|
||||
|
||||
**Version 0.34** adds components as views, which allows you to handle requests and render responses from within a component. See the [documentation](#components-as-views) for more details.
|
||||
|
||||
**Version 0.28** introduces 'implicit' slot filling and the `default` option for `slot` tags.
|
||||
|
||||
**Version 0.27** adds a second installable app: *django_components.safer_staticfiles*. It provides the same behavior as *django.contrib.staticfiles* but with extra security guarantees (more info below in Security Notes).
|
||||
|
||||
**Version 0.26** changes the syntax for `{% slot %}` tags. From now on, we separate defining a slot (`{% slot %}`) from filling a slot with content (`{% fill %}`). This means you will likely need to change a lot of slot tags to fill. We understand this is annoying, but it's the only way we can get support for nested slots that fill in other slots, which is a very nice featuPpre to have access to. Hoping that this will feel worth it!
|
||||
|
||||
**Version 0.22** starts autoimporting all files inside components subdirectores, to simplify setup. An existing project might start to get AlreadyRegistered-errors because of this. To solve this, either remove your custom loading of components, or set "autodiscover": False in settings.COMPONENTS.
|
||||
|
||||
**Version 0.17** renames `Component.context` and `Component.template` to `get_context_data` and `get_template_name`. The old methods still work, but emit a deprecation warning. This change was done to sync naming with Django's class based views, and make using django-components more familiar to Django users. `Component.context` and `Component.template` will be removed when version 1.0 is released.
|
1
docs/CODE_OF_CONDUCT.md
Normal file
1
docs/CODE_OF_CONDUCT.md
Normal file
|
@ -0,0 +1 @@
|
|||
--8<-- "CODE_OF_CONDUCT.md"
|
85
docs/dev_guide/index.md
Normal file
85
docs/dev_guide/index.md
Normal file
|
@ -0,0 +1,85 @@
|
|||
---
|
||||
hide:
|
||||
- navigation
|
||||
---
|
||||
|
||||
# Development guide
|
||||
|
||||
## Running django-components project locally
|
||||
|
||||
### Install locally and run the tests
|
||||
|
||||
Start by forking the project by clicking the **Fork button** up in the right corner in the GitHub . This makes a copy of the repository in your own name. Now you can clone this repository locally and start adding features:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/<your GitHub username>/django-components.git
|
||||
```
|
||||
|
||||
To quickly run the tests install the local dependencies by running:
|
||||
|
||||
```sh
|
||||
pip install -r requirements-dev.txt
|
||||
```
|
||||
|
||||
Now you can run the tests to make sure everything works as expected:
|
||||
|
||||
```sh
|
||||
pytest
|
||||
```
|
||||
|
||||
The library is also tested across many versions of Python and Django. To run tests that way:
|
||||
|
||||
```bash
|
||||
pyenv install -s 3.7
|
||||
pyenv install -s 3.8
|
||||
pyenv install -s 3.9
|
||||
pyenv install -s 3.10
|
||||
pyenv install -s 3.11
|
||||
pyenv install -s 3.12
|
||||
pyenv local 3.6 3.7 3.8 3.9 3.10 3.11 3.12
|
||||
tox -p
|
||||
```
|
||||
|
||||
### Developing against live Django app
|
||||
|
||||
How do you check that your changes to django-components project will work in an actual Django project?
|
||||
|
||||
Use the [sampleproject](https://github.com/EmilStenstrom/django-components/tree/master/sampleproject/) demo project to validate the changes:
|
||||
|
||||
1. Navigate to [sampleproject](https://github.com/EmilStenstrom/django-components/tree/master/sampleproject/) directory:
|
||||
```sh
|
||||
cd sampleproject
|
||||
```
|
||||
|
||||
2. Install dependencies from the [requirements.txt](https://github.com/EmilStenstrom/django-components/tree/master/sampleproject/requirements.txt) file:
|
||||
```sh
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. Link to your local version of django-components:
|
||||
```sh
|
||||
pip install -e ..
|
||||
```
|
||||
NOTE: The path (in this case `..`) must point to the directory that has the `setup.py` file.
|
||||
|
||||
4. Start Django server
|
||||
```sh
|
||||
python manage.py runserver
|
||||
```
|
||||
|
||||
Once the server is up, it should be available at <http://127.0.0.1:8000>.
|
||||
|
||||
To display individual components, add them to the `urls.py`, like in the case of <http://127.0.0.1:8000/greeting>
|
||||
|
||||
## Slot rendering flow
|
||||
|
||||
1. Flow starts when a template string is being parsed into Django Template instance.
|
||||
|
||||
2. When a `{% component %}` template tag is encountered, its body is searched for all `{% fill %}` nodes (explicit or implicit). and this is attached to the created [`ComponentNode`][django_components.component.ComponentNode].
|
||||
|
||||
See the implementation of [`component`][django_components.templatetags.component_tags.do_component] template tag for details.
|
||||
|
||||
3. Template rendering is a separate action from template parsing. When the template is being rendered, the [`ComponentNode`][django_components.component.ComponentNode] creates an instance of the [`Component`][django_components.component.Component] class and passes it the slot fills.
|
||||
|
||||
It's at this point when [`Component.render`][django_components.component.Component.render] is called, and the slots are
|
||||
rendered.
|
1
docs/index.md
Normal file
1
docs/index.md
Normal file
|
@ -0,0 +1 @@
|
|||
--8<-- "README.md"
|
5
docs/license.md
Normal file
5
docs/license.md
Normal file
|
@ -0,0 +1,5 @@
|
|||
# License
|
||||
|
||||
```
|
||||
--8<-- "LICENSE"
|
||||
```
|
24
docs/reference/SUMMARY.md
Normal file
24
docs/reference/SUMMARY.md
Normal file
|
@ -0,0 +1,24 @@
|
|||
* <code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> django_components
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> __init__](django_components/__init__.md/index.md)
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> app_settings](django_components/app_settings.md/index.md)
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> apps](django_components/apps.md/index.md)
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> component](django_components/component.md/index.md)
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> component_registry](django_components/component_registry.md/index.md)
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> logger](django_components/logger.md/index.md)
|
||||
* <code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> management
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> __init__](django_components/management/__init__.md/index.md)
|
||||
* <code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> commands
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> __init__](django_components/management/commands/__init__.md/index.md)
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> startcomponent](django_components/management/commands/startcomponent.md/index.md)
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> upgradecomponent](django_components/management/commands/upgradecomponent.md/index.md)
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> middleware](django_components/middleware.md/index.md)
|
||||
* <code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> safer_staticfiles
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> __init__](django_components/safer_staticfiles/__init__.md/index.md)
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> apps](django_components/safer_staticfiles/apps.md/index.md)
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> slots](django_components/slots.md/index.md)
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> template_loader](django_components/template_loader.md/index.md)
|
||||
* <code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> templatetags
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> __init__](django_components/templatetags/__init__.md/index.md)
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> component_tags](django_components/templatetags/component_tags.md/index.md)
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> types](django_components/types.md/index.md)
|
||||
* [<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code> utils](django_components/utils.md/index.md)
|
1
docs/reference/django_components/__init__.md/index.md
Normal file
1
docs/reference/django_components/__init__.md/index.md
Normal file
|
@ -0,0 +1 @@
|
|||
::: django_components
|
|
@ -0,0 +1 @@
|
|||
::: django_components.app_settings
|
1
docs/reference/django_components/apps.md/index.md
Normal file
1
docs/reference/django_components/apps.md/index.md
Normal file
|
@ -0,0 +1 @@
|
|||
::: django_components.apps
|
1
docs/reference/django_components/component.md/index.md
Normal file
1
docs/reference/django_components/component.md/index.md
Normal file
|
@ -0,0 +1 @@
|
|||
::: django_components.component
|
|
@ -0,0 +1 @@
|
|||
::: django_components.component_registry
|
1
docs/reference/django_components/logger.md/index.md
Normal file
1
docs/reference/django_components/logger.md/index.md
Normal file
|
@ -0,0 +1 @@
|
|||
::: django_components.logger
|
|
@ -0,0 +1 @@
|
|||
::: django_components.management
|
|
@ -0,0 +1 @@
|
|||
::: django_components.management.commands
|
|
@ -0,0 +1 @@
|
|||
::: django_components.management.commands.startcomponent
|
|
@ -0,0 +1 @@
|
|||
::: django_components.management.commands.upgradecomponent
|
1
docs/reference/django_components/middleware.md/index.md
Normal file
1
docs/reference/django_components/middleware.md/index.md
Normal file
|
@ -0,0 +1 @@
|
|||
::: django_components.middleware
|
|
@ -0,0 +1 @@
|
|||
::: django_components.safer_staticfiles
|
|
@ -0,0 +1 @@
|
|||
::: django_components.safer_staticfiles.apps
|
1
docs/reference/django_components/slots.md/index.md
Normal file
1
docs/reference/django_components/slots.md/index.md
Normal file
|
@ -0,0 +1 @@
|
|||
::: django_components.slots
|
|
@ -0,0 +1 @@
|
|||
::: django_components.template_loader
|
|
@ -0,0 +1 @@
|
|||
::: django_components.templatetags
|
|
@ -0,0 +1 @@
|
|||
::: django_components.templatetags.component_tags
|
1
docs/reference/django_components/types.md/index.md
Normal file
1
docs/reference/django_components/types.md/index.md
Normal file
|
@ -0,0 +1 @@
|
|||
::: django_components.types
|
1
docs/reference/django_components/utils.md/index.md
Normal file
1
docs/reference/django_components/utils.md/index.md
Normal file
|
@ -0,0 +1 @@
|
|||
::: django_components.utils
|
73
docs/user_guide/commands.md
Normal file
73
docs/user_guide/commands.md
Normal file
|
@ -0,0 +1,73 @@
|
|||
# Management Command
|
||||
|
||||
You can use the built-in management command `startcomponent` to create a django component. The command accepts the following arguments and options:
|
||||
|
||||
- `name`: The name of the component to create. This is a required argument.
|
||||
|
||||
- `--path`: The path to the components directory. This is an optional argument. If not provided, the command will use the `BASE_DIR` setting from your Django settings.
|
||||
|
||||
- `--js`: The name of the JavaScript file. This is an optional argument. The default value is `script.js`.
|
||||
|
||||
- `--css`: The name of the CSS file. This is an optional argument. The default value is `style.css`.
|
||||
|
||||
- `--template`: The name of the template file. This is an optional argument. The default value is `template.html`.
|
||||
|
||||
- `--force`: This option allows you to overwrite existing files if they exist. This is an optional argument.
|
||||
|
||||
- `--verbose`: This option allows the command to print additional information during component creation. This is an optional argument.
|
||||
|
||||
- `--dry-run`: This option allows you to simulate component creation without actually creating any files. This is an optional argument. The default value is `False`.
|
||||
|
||||
### Management Command Usage
|
||||
|
||||
To use the command, run the following command in your terminal:
|
||||
|
||||
```bash
|
||||
python manage.py startcomponent <name> --path <path> --js <js_filename> --css <css_filename> --template <template_filename> --force --verbose --dry-run
|
||||
```
|
||||
|
||||
Replace `<name>`, `<path>`, `<js_filename>`, `<css_filename>`, and `<template_filename>` with your desired values.
|
||||
|
||||
### Management Command Examples
|
||||
|
||||
Here are some examples of how you can use the command:
|
||||
|
||||
### Creating a Component with Default Settings
|
||||
|
||||
To create a component with the default settings, you only need to provide the name of the component:
|
||||
|
||||
```bash
|
||||
python manage.py startcomponent my_component
|
||||
```
|
||||
|
||||
This will create a new component named `my_component` in the `components` directory of your Django project. The JavaScript, CSS, and template files will be named `script.js`, `style.css`, and `template.html`, respectively.
|
||||
|
||||
### Creating a Component with Custom Settings
|
||||
|
||||
You can also create a component with custom settings by providing additional arguments:
|
||||
|
||||
```bash
|
||||
python manage.py startcomponent new_component --path my_components --js my_script.js --css my_style.css --template my_template.html
|
||||
```
|
||||
|
||||
This will create a new component named `new_component` in the `my_components` directory. The JavaScript, CSS, and template files will be named `my_script.js`, `my_style.css`, and `my_template.html`, respectively.
|
||||
|
||||
### Overwriting an Existing Component
|
||||
|
||||
If you want to overwrite an existing component, you can use the `--force` option:
|
||||
|
||||
```bash
|
||||
python manage.py startcomponent my_component --force
|
||||
```
|
||||
|
||||
This will overwrite the existing `my_component` if it exists.
|
||||
|
||||
### Simulating Component Creation
|
||||
|
||||
If you want to simulate the creation of a component without actually creating any files, you can use the `--dry-run` option:
|
||||
|
||||
```bash
|
||||
python manage.py startcomponent my_component --dry-run
|
||||
```
|
||||
|
||||
This will simulate the creation of `my_component` without creating any files.
|
117
docs/user_guide/creating_using_components/advanced.md
Normal file
117
docs/user_guide/creating_using_components/advanced.md
Normal file
|
@ -0,0 +1,117 @@
|
|||
# Advanced
|
||||
|
||||
## Re-using content defined in the original slot
|
||||
|
||||
Certain properties of a slot can be accessed from within a 'fill' context. They are provided as attributes on a user-defined alias of the targeted slot. For instance, let's say you're filling a slot called 'body'. To access properties of this slot, alias it using the 'as' keyword to a new name -- or keep the original name. With the new slot alias, you can call `<alias>.default` to insert the default content.
|
||||
|
||||
```htmldjango
|
||||
{% component "calendar" date="2020-06-06" %}
|
||||
{% fill "body" as "body" %}{{ body.default }}. Have a great day!{% endfill %}
|
||||
{% endcomponent %}
|
||||
```
|
||||
|
||||
Produces:
|
||||
|
||||
```htmldjango
|
||||
<div class="calendar-component">
|
||||
<div class="header">
|
||||
Calendar header
|
||||
</div>
|
||||
<div class="body">
|
||||
Today's date is <span>2020-06-06</span>. Have a great day!
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
|
||||
## Conditional slots
|
||||
|
||||
_Added in version 0.26._
|
||||
|
||||
In certain circumstances, you may want the behavior of slot filling to depend on
|
||||
whether or not a particular slot is filled.
|
||||
|
||||
For example, suppose we have the following component template:
|
||||
|
||||
```htmldjango
|
||||
<div class="frontmatter-component">
|
||||
<div class="title">
|
||||
{% slot "title" %}Title{% endslot %}
|
||||
</div>
|
||||
<div class="subtitle">
|
||||
{% slot "subtitle" %}{# Optional subtitle #}{% endslot %}
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
By default the slot named 'subtitle' is empty. Yet when the component is used without
|
||||
explicit fills, the div containing the slot is still rendered, as shown below:
|
||||
|
||||
```html
|
||||
<div class="frontmatter-component">
|
||||
<div class="title">
|
||||
Title
|
||||
</div>
|
||||
<div class="subtitle">
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
This may not be what you want. What if instead the outer 'subtitle' div should only
|
||||
be included when the inner slot is in fact filled?
|
||||
|
||||
The answer is to use the `{% if_filled <name> %}` tag. Together with `{% endif_filled %}`,
|
||||
these define a block whose contents will be rendered only if the component slot with
|
||||
the corresponding 'name' is filled.
|
||||
|
||||
This is what our example looks like with an 'if_filled' tag.
|
||||
|
||||
```htmldjango
|
||||
<div class="frontmatter-component">
|
||||
<div class="title">
|
||||
{% slot "title" %}Title{% endslot %}
|
||||
</div>
|
||||
{% if_filled "subtitle" %}
|
||||
<div class="subtitle">
|
||||
{% slot "subtitle" %}{# Optional subtitle #}{% endslot %}
|
||||
</div>
|
||||
{% endif_filled %}
|
||||
</div>
|
||||
```
|
||||
|
||||
Just as Django's builtin 'if' tag has 'elif' and 'else' counterparts, so does 'if_filled'
|
||||
include additional tags for more complex branching. These tags are 'elif_filled' and
|
||||
'else_filled'. Here's what our example looks like with them.
|
||||
|
||||
```htmldjango
|
||||
<div class="frontmatter-component">
|
||||
<div class="title">
|
||||
{% slot "title" %}Title{% endslot %}
|
||||
</div>
|
||||
{% if_filled "subtitle" %}
|
||||
<div class="subtitle">
|
||||
{% slot "subtitle" %}{# Optional subtitle #}{% endslot %}
|
||||
</div>
|
||||
{% elif_filled "title" %}
|
||||
...
|
||||
{% else_filled %}
|
||||
...
|
||||
{% endif_filled %}
|
||||
</div>
|
||||
```
|
||||
|
||||
Sometimes you're not interested in whether a slot is filled, but rather that it _isn't_.
|
||||
To negate the meaning of 'if_filled' in this way, an optional boolean can be passed to
|
||||
the 'if_filled' and 'elif_filled' tags.
|
||||
|
||||
In the example below we use `False` to indicate that the content should be rendered
|
||||
only if the slot 'subtitle' is _not_ filled.
|
||||
|
||||
```htmldjango
|
||||
{% if_filled subtitle False %}
|
||||
<div class="subtitle">
|
||||
{% slot "subtitle" %}{% endslot %}
|
||||
</div>
|
||||
{% endif_filled %}
|
||||
```
|
||||
|
13
docs/user_guide/creating_using_components/context_scope.md
Normal file
13
docs/user_guide/creating_using_components/context_scope.md
Normal file
|
@ -0,0 +1,13 @@
|
|||
# Component context and scope
|
||||
|
||||
By default, components can access context variables from the parent template, just like templates that are included with the `{% include %}` tag. Just like with `{% include %}`, if you don't want the component template to have access to the parent context, add `only` to the end of the `{% component %}` tag):
|
||||
|
||||
```htmldjango
|
||||
{% component "calendar" date="2015-06-19" only %}{% endcomponent %}
|
||||
```
|
||||
|
||||
NOTE: `{% csrf_token %}` tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the `only` modifier.
|
||||
|
||||
Components can also access the outer context in their context methods by accessing the property `outer_context`.
|
||||
|
||||
You can also set `context_behavior` to `isolated` to make all components isolated by default. This is useful if you want to make sure that components don't accidentally access the outer context.
|
|
@ -0,0 +1,56 @@
|
|||
# Create your first component
|
||||
|
||||
A component in django-components is the combination of four things: CSS, Javascript, a Django template, and some Python code to put them all together.
|
||||
|
||||

|
||||
|
||||
Start by creating empty files in the structure above.
|
||||
|
||||
First you need a CSS file. Be sure to prefix all rules with a unique class so they don't clash with other rules.
|
||||
|
||||
```css title="[project root]/components/calendar/style.css"
|
||||
.calendar-component { width: 200px; background: pink; }
|
||||
.calendar-component span { font-weight: bold; }
|
||||
```
|
||||
|
||||
Then you need a javascript file that specifies how you interact with this component. You are free to use any javascript framework you want. A good way to make sure this component doesn't clash with other components is to define all code inside an anonymous function that calls itself. This makes all variables defined only be defined inside this component and not affect other components.
|
||||
|
||||
```js title="[project root]/components/calendar/script.js"
|
||||
(function(){
|
||||
if (document.querySelector(".calendar-component")) {
|
||||
document.querySelector(".calendar-component").onclick = function(){ alert("Clicked calendar!"); };
|
||||
}
|
||||
})()
|
||||
```
|
||||
|
||||
Now you need a Django template for your component. Feel free to define more variables like `date` in this example. When creating an instance of this component we will send in the values for these variables. The template will be rendered with whatever template backend you've specified in your Django settings file.
|
||||
|
||||
```htmldjango title="[project root]/components/calendar/calendar.html"
|
||||
<div class="calendar-component">Today's date is <span>{{ date }}</span></div>
|
||||
```
|
||||
|
||||
Finally, we use django-components to tie this together. Start by creating a file called `calendar.py` in your component calendar directory. It will be auto-detected and loaded by the app.
|
||||
|
||||
Inside this file we create a Component by inheriting from the Component class and specifying the context method. We also register the global component registry so that we easily can render it anywhere in our templates.
|
||||
|
||||
```python title="[project root]/components/calendar/calendar.py"
|
||||
from django_components import component
|
||||
|
||||
@component.register("calendar")
|
||||
class Calendar(component.Component):
|
||||
# Templates inside `[your apps]/components` dir and `[project root]/components` dir will be automatically found. To customize which template to use based on context
|
||||
# you can override def get_template_name() instead of specifying the below variable.
|
||||
template_name = "calendar.html"
|
||||
|
||||
# This component takes one parameter, a date string to show in the template
|
||||
def get_context_data(self, date):
|
||||
return {
|
||||
"date": date,
|
||||
}
|
||||
|
||||
class Media:
|
||||
css = "style.css"
|
||||
js = "script.js"
|
||||
```
|
||||
|
||||
And voilà!! We've created our first component.
|
22
docs/user_guide/creating_using_components/middleware.md
Normal file
22
docs/user_guide/creating_using_components/middleware.md
Normal file
|
@ -0,0 +1,22 @@
|
|||
# Setting Up `ComponentDependencyMiddleware`
|
||||
|
||||
[`ComponentDependencyMiddleware`][django_components.middleware.ComponentDependencyMiddleware] is a Django middleware designed to manage and inject CSS/JS dependencies for rendered components dynamically. It ensures that only the necessary stylesheets and scripts are loaded in your HTML responses, based on the components used in your Django templates.
|
||||
|
||||
To set it up, add the middleware to your [`MIDDLEWARE`][] in settings.py:
|
||||
|
||||
```python
|
||||
MIDDLEWARE = [
|
||||
# ... other middleware classes ...
|
||||
'django_components.middleware.ComponentDependencyMiddleware'
|
||||
# ... other middleware classes ...
|
||||
]
|
||||
```
|
||||
|
||||
Then, enable `RENDER_DEPENDENCIES` in setting.py:
|
||||
|
||||
```python
|
||||
COMPONENTS = {
|
||||
"RENDER_DEPENDENCIES": True,
|
||||
# ... other component settings ...
|
||||
}
|
||||
```
|
|
@ -0,0 +1,36 @@
|
|||
# Using single-file components
|
||||
|
||||
Components can also be defined in a single file, which is useful for small components. To do this, you can use the `template`, `js`, and `css` class attributes instead of the `template_name` and `Media`. For example, here's the calendar component from above, defined in a single file:
|
||||
|
||||
```python title="[project root]/components/calendar.py"
|
||||
from django_components import component
|
||||
from django_components import types as t
|
||||
|
||||
@component.register("calendar")
|
||||
class Calendar(component.Component):
|
||||
def get_context_data(self, date):
|
||||
return {
|
||||
"date": date,
|
||||
}
|
||||
|
||||
template: t.django_html = """
|
||||
<div class="calendar-component">Today's date is <span>{{ date }}</span></div>
|
||||
"""
|
||||
|
||||
css: t.css = """
|
||||
.calendar-component { width: 200px; background: pink; }
|
||||
.calendar-component span { font-weight: bold; }
|
||||
"""
|
||||
|
||||
js: t.js = """
|
||||
(function(){
|
||||
if (document.querySelector(".calendar-component")) {
|
||||
document.querySelector(".calendar-component").onclick = function(){ alert("Clicked calendar!"); };
|
||||
}
|
||||
})()
|
||||
"""
|
||||
```
|
||||
|
||||
This makes it easy to create small components without having to create a separate template, CSS, and JS file.
|
||||
|
||||
Note that the `t.django_html`, `t.css`, and `t.js` types are used to specify the type of the template, CSS, and JS files, respectively. This is not necessary, but if you're using VSCode with the [Python Inline Source Syntax Highlighting](https://marketplace.visualstudio.com/items?itemName=samwillis.python-inline-source) extension, it will give you syntax highlighting for the template, CSS, and JS.
|
37
docs/user_guide/creating_using_components/use_component.md
Normal file
37
docs/user_guide/creating_using_components/use_component.md
Normal file
|
@ -0,0 +1,37 @@
|
|||
|
||||
# Use the component in a template
|
||||
|
||||
First load the [`component_tags`][django_components.templatetags.component_tags] tag library, then use the `component_[js/css]_dependencies` and [`component`][django_components.templatetags.component_tags.do_component] tags to render the component to the page.
|
||||
|
||||
```htmldjango
|
||||
{% load component_tags %}
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>My example calendar</title>
|
||||
{% component_css_dependencies %}
|
||||
</head>
|
||||
<body>
|
||||
{% component "calendar" date="2015-06-19" %}{% endcomponent %}
|
||||
{% component_js_dependencies %}
|
||||
</body>
|
||||
<html>
|
||||
```
|
||||
|
||||
The output from the above template will be:
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>My example calendar</title>
|
||||
<link href="style.css" type="text/css" media="all" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div class="calendar-component">Today's date is <span>2015-06-19</span></div>
|
||||
<script src="script.js"></script>
|
||||
</body>
|
||||
<html>
|
||||
```
|
||||
|
||||
This makes it possible to organize your front-end around reusable components. Instead of relying on template tags and keeping your CSS and Javascript in the static directory.
|
190
docs/user_guide/creating_using_components/using_slots.md
Normal file
190
docs/user_guide/creating_using_components/using_slots.md
Normal file
|
@ -0,0 +1,190 @@
|
|||
|
||||
# Using slots in templates
|
||||
|
||||
_New in version 0.26_:
|
||||
|
||||
- The `slot` tag now serves only to declare new slots inside the component template.
|
||||
- To override the content of a declared slot, use the newly introduced `fill` tag instead.
|
||||
- Whereas unfilled slots used to raise a warning, filling a slot is now optional by default.
|
||||
- To indicate that a slot must be filled, the new `required` option should be added at the end of the `slot` tag.
|
||||
|
||||
---
|
||||
|
||||
Components support something called 'slots'.
|
||||
When a component is used inside another template, slots allow the parent template to override specific parts of the child component by passing in different content.
|
||||
This mechanism makes components more reusable and composable.
|
||||
|
||||
In the example below we introduce two block tags that work hand in hand to make this work. These are...
|
||||
|
||||
- `{% slot <name> %}`/`{% endslot %}`: Declares a new slot in the component template.
|
||||
- `{% fill <name> %}`/`{% endfill %}`: (Used inside a `component` tag pair.) Fills a declared slot with the specified content.
|
||||
|
||||
Let's update our calendar component to support more customization. We'll add `slot` tag pairs to its template, _calendar.html_.
|
||||
|
||||
```htmldjango
|
||||
<div class="calendar-component">
|
||||
<div class="header">
|
||||
{% slot "header" %}Calendar header{% endslot %}
|
||||
</div>
|
||||
<div class="body">
|
||||
{% slot "body" %}Today's date is <span>{{ date }}</span>{% endslot %}
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
When using the component, you specify which slots you want to fill and where you want to use the defaults from the template. It looks like this:
|
||||
|
||||
```htmldjango
|
||||
{% component "calendar" date="2020-06-06" %}
|
||||
{% fill "body" %}Can you believe it's already <span>{{ date }}</span>??{% endfill %}
|
||||
{% endcomponent %}
|
||||
```
|
||||
|
||||
Since the header block is unspecified, it's taken from the base template. If you put this in a template, and pass in `date=2020-06-06`, this is what gets rendered:
|
||||
|
||||
```htmldjango
|
||||
<div class="calendar-component">
|
||||
<div class="header">
|
||||
Calendar header
|
||||
</div>
|
||||
<div class="body">
|
||||
Can you believe it's already <span>2020-06-06</span>??
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
As you can see, component slots lets you write reusable containers that you fill in when you use a component. This makes for highly reusable components that can be used in different circumstances.
|
||||
|
||||
It can become tedious to use `fill` tags everywhere, especially when you're using a component that declares only one slot. To make things easier, `slot` tags can be marked with an optional keyword: `default`. When added to the end of the tag (as shown below), this option lets you pass filling content directly in the body of a `component` tag pair – without using a `fill` tag. Choose carefully, though: a component template may contain at most one slot that is marked as `default`. The `default` option can be combined with other slot options, e.g. `required`.
|
||||
|
||||
Here's the same example as before, except with default slots and implicit filling.
|
||||
|
||||
The template:
|
||||
|
||||
```htmldjango
|
||||
<div class="calendar-component">
|
||||
<div class="header">
|
||||
{% slot "header" %}Calendar header{% endslot %}
|
||||
</div>
|
||||
<div class="body">
|
||||
{% slot "body" default %}Today's date is <span>{{ date }}</span>{% endslot %}
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
Including the component (notice how the `fill` tag is omitted):
|
||||
|
||||
```htmldjango
|
||||
{% component "calendar" date="2020-06-06" %}
|
||||
Can you believe it's already <span>{{ date }}</span>??
|
||||
{% endcomponent %}
|
||||
```
|
||||
|
||||
The rendered result (exactly the same as before):
|
||||
|
||||
```html
|
||||
<div class="calendar-component">
|
||||
<div class="header">
|
||||
Calendar header
|
||||
</div>
|
||||
<div class="body">
|
||||
Can you believe it's already <span>2020-06-06</span>??
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
You may be tempted to combine implicit fills with explicit `fill` tags. This will not work. The following component template will raise an error when compiled.
|
||||
|
||||
```htmldjango
|
||||
{# DON'T DO THIS #}
|
||||
{% component "calendar" date="2020-06-06" %}
|
||||
{% fill "header" %}Totally new header!{% endfill %}
|
||||
Can you believe it's already <span>{{ date }}</span>??
|
||||
{% endcomponent %}
|
||||
```
|
||||
|
||||
By contrast, it is permitted to use `fill` tags in nested components, e.g.:
|
||||
|
||||
```htmldjango
|
||||
{% component "calendar" date="2020-06-06" %}
|
||||
{% component "beautiful-box" %}
|
||||
{% fill "content" %} Can you believe it's already <span>{{ date }}</span>?? {% endfill %}
|
||||
{% endcomponent %}
|
||||
{% endcomponent %}
|
||||
```
|
||||
|
||||
This is fine too:
|
||||
|
||||
```htmldjango
|
||||
{% component "calendar" date="2020-06-06" %}
|
||||
{% fill "header" %}
|
||||
{% component "calendar-header" %}
|
||||
Super Special Calendar Header
|
||||
{% endcomponent %}
|
||||
{% endfill %}
|
||||
{% endcomponent %}
|
||||
```
|
||||
|
||||
## Components as views
|
||||
|
||||
_New in version 0.34_
|
||||
|
||||
Components can now be used as views. To do this, [`Component`][django_components.component.Component] subclasses Django's [`View`][] class. This means that you can use all of the [methods](https://docs.djangoproject.com/en/5.0/ref/class-based-views/base/#view) of `View` in your component. For example, you can override `get` and `post` to handle GET and POST requests, respectively.
|
||||
|
||||
In addition, [`Component`][django_components.component.Component] now has a [`render_to_response`][django_components.component.Component.render_to_response] method that renders the component template based on the provided context and slots' data and returns an [`HttpResponse`][django.http.HttpResponse] object.
|
||||
|
||||
Here's an example of a calendar component defined as a view:
|
||||
|
||||
```python title="[project root]/components/calendar.py"
|
||||
from django_components import component
|
||||
|
||||
@component.register("calendar")
|
||||
class Calendar(component.Component):
|
||||
|
||||
template = """
|
||||
<div class="calendar-component">
|
||||
<div class="header">
|
||||
{% slot "header" %}{% endslot %}
|
||||
</div>
|
||||
<div class="body">
|
||||
Today's date is <span>{{ date }}</span>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
context = {
|
||||
"date": request.GET.get("date", "2020-06-06"),
|
||||
}
|
||||
slots = {
|
||||
"header": "Calendar header",
|
||||
}
|
||||
return self.render_to_response(context, slots)
|
||||
```
|
||||
|
||||
Then, to use this component as a view, you should create a `urls.py` file in your components directory, and add a path to the component's view:
|
||||
|
||||
```python title="[project root]/components/urls.py"
|
||||
from django.urls import path
|
||||
from calendar import Calendar
|
||||
|
||||
urlpatterns = [
|
||||
path("calendar/", Calendar.as_view()),
|
||||
]
|
||||
```
|
||||
|
||||
Remember to add `__init__.py` to your components directory, so that Django can find the `urls.py` file.
|
||||
|
||||
Finally, include the component's urls in your project's `urls.py` file:
|
||||
|
||||
```python title="[project root]/urls.py"
|
||||
from django.urls import include, path
|
||||
|
||||
urlpatterns = [
|
||||
path("components/", include("components.urls")),
|
||||
]
|
||||
```
|
||||
|
||||
Note: slots content are automatically escaped by default to prevent XSS attacks. To disable escaping, set `escape_slots_content=False` in the `render_to_response` method. If you do so, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
|
||||
|
||||
If you're planning on passing an HTML string, check Django's use of [`format_html`](https://docs.djangoproject.com/en/5.0/ref/utils/#django.utils.html.format_html) and [`mark_safe`](https://docs.djangoproject.com/en/5.0/ref/utils/#django.utils.safestring.mark_safe).
|
0
docs/user_guide/getting_started.md
Normal file
0
docs/user_guide/getting_started.md
Normal file
1
docs/user_guide/index.md
Normal file
1
docs/user_guide/index.md
Normal file
|
@ -0,0 +1 @@
|
|||
[TOC]
|
71
docs/user_guide/installation.md
Normal file
71
docs/user_guide/installation.md
Normal file
|
@ -0,0 +1,71 @@
|
|||
# Installation
|
||||
|
||||
Install the app into your environment:
|
||||
|
||||
> ```pip install django-components```
|
||||
|
||||
Then add the app into [`INSTALLED_APPS`][INSTALLED_APPS] in settings.py
|
||||
|
||||
```python
|
||||
INSTALLED_APPS = [
|
||||
...,
|
||||
'django_components',
|
||||
]
|
||||
```
|
||||
|
||||
Modify [`TEMPLATES`][TEMPLATES] section of settings.py as follows:
|
||||
|
||||
|
||||
- *Remove `'APP_DIRS': True,`*
|
||||
- add `loaders` to [`OPTIONS`][TEMPLATES-OPTIONS] list and set it to following value:
|
||||
|
||||
```python
|
||||
TEMPLATES = [
|
||||
{
|
||||
...,
|
||||
'OPTIONS': {
|
||||
'context_processors': [
|
||||
...
|
||||
],
|
||||
'loaders':[(
|
||||
'django.template.loaders.cached.Loader', [
|
||||
'django.template.loaders.filesystem.Loader',
|
||||
'django.template.loaders.app_directories.Loader',
|
||||
'django_components.template_loader.Loader',
|
||||
]
|
||||
)],
|
||||
},
|
||||
},
|
||||
]
|
||||
```
|
||||
|
||||
Modify [`STATICFILES_DIRS`][STATICFILES_DIRS] (or add it if you don't have it) so django can find your static JS and CSS files:
|
||||
|
||||
```python
|
||||
STATICFILES_DIRS = [
|
||||
...,
|
||||
os.path.join(BASE_DIR, "components"),
|
||||
]
|
||||
```
|
||||
|
||||
## _Optional_: Load django-components in all templates
|
||||
|
||||
To avoid loading the app in each template using ``` {% load django_components %} ```, you can add the tag as a 'builtin' in settings.py
|
||||
|
||||
```python
|
||||
TEMPLATES = [
|
||||
{
|
||||
...,
|
||||
'OPTIONS': {
|
||||
'context_processors': [
|
||||
...
|
||||
],
|
||||
'builtins': [
|
||||
'django_components.templatetags.component_tags',
|
||||
]
|
||||
},
|
||||
},
|
||||
]
|
||||
```
|
||||
|
||||
Read on to find out how to build your first component!
|
29
docs/user_guide/logging_debugging.md
Normal file
29
docs/user_guide/logging_debugging.md
Normal file
|
@ -0,0 +1,29 @@
|
|||
# Logging and debugging
|
||||
|
||||
Django components supports [logging with Django](https://docs.djangoproject.com/en/5.0/howto/logging/#logging-how-to). This can help with troubleshooting.
|
||||
|
||||
To configure logging for Django components, set the `django_components` logger in `LOGGING` in `settings.py` (below).
|
||||
|
||||
Also see the [`settings.py` file in sampleproject](https://github.com/EmilStenstrom/django-components/tree/master/sampleproject/sampleproject/settings.py) for a real-life example.
|
||||
|
||||
```py
|
||||
import logging
|
||||
import sys
|
||||
|
||||
LOGGING = {
|
||||
'version': 1,
|
||||
'disable_existing_loggers': False,
|
||||
"handlers": {
|
||||
"console": {
|
||||
'class': 'logging.StreamHandler',
|
||||
'stream': sys.stdout,
|
||||
},
|
||||
},
|
||||
"loggers": {
|
||||
"django_components": {
|
||||
"level": logging.DEBUG,
|
||||
"handlers": ["console"],
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
15
docs/user_guide/requirements_compatibility.md
Normal file
15
docs/user_guide/requirements_compatibility.md
Normal file
|
@ -0,0 +1,15 @@
|
|||
|
||||
# Compatibility and requirements
|
||||
|
||||
Django-components supports all <a href="https://docs.djangoproject.com/en/dev/faq/install/#what-python-version-can-i-use-with-django">officially supported versions</a> of Django and Python.
|
||||
|
||||
| Python version | Django version |
|
||||
|----------------|--------------------------|
|
||||
| 3.7 | 3.2 |
|
||||
| 3.8 | 3.2, 4.0, 4.1, 4.2 |
|
||||
| 3.9 | 3.2, 4.0, 4.1, 4.2 |
|
||||
| 3.10 | 3.2, 4.0, 4.1, 4.2, 5.0 |
|
||||
| 3.11 | 4.1, 4.2, 5.0 |
|
||||
| 3.12 | 4.2, 5.0 |
|
||||
|
||||
For each version of Django and Python, we recommend using the latest micro release (A.B.C).
|
30
docs/user_guide/security.md
Normal file
30
docs/user_guide/security.md
Normal file
|
@ -0,0 +1,30 @@
|
|||
|
||||
# Security notes 🚨
|
||||
|
||||
*You are advised to read this section before using django-components in production.*
|
||||
|
||||
### Static files
|
||||
|
||||
Components can be organized however you prefer.
|
||||
That said, our prefered way is to keep the files of a component close together by bundling them in the same directory.
|
||||
This means that files containing backend logic, such as Python modules and HTML templates, live in the same directory as static files, e.g. JS and CSS.
|
||||
|
||||
If your are using [`django.contrib.staticfiles`][] to collect static files, no distinction is made between the different kinds of files.
|
||||
As a result, your Python code and templates may inadvertently become available on your static file server.
|
||||
You probably don't want this, as parts of your backend logic will be exposed, posing a __potential security vulnerability__.
|
||||
|
||||
As of *v0.27*, django-components ships with an additional installable app *[`django_components.safer_staticfiles`][]*.
|
||||
It is a drop-in replacement for *[`django.contrib.staticfiles`][]*.
|
||||
Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server.
|
||||
To use it, add it to [`INSTALLED_APPS`][] and remove [`django.contrib.staticfiles`].
|
||||
|
||||
```python
|
||||
INSTALLED_APPS = [
|
||||
# 'django.contrib.staticfiles', # <-- REMOVE
|
||||
'django_components',
|
||||
'django_components.safer_staticfiles' # <-- ADD
|
||||
]
|
||||
```
|
||||
|
||||
If you are on an older version of django-components, your alternatives are a) passing `--ignore <pattern>` options to the _collecstatic_ CLI command, or b) defining a subclass of `StaticFilesConfig`.
|
||||
Both routes are described in the official [docs of the _staticfiles_ app](https://docs.djangoproject.com/en/4.2/ref/contrib/staticfiles/#customizing-the-ignored-pattern-list).
|
58
docs/user_guide/settings.md
Normal file
58
docs/user_guide/settings.md
Normal file
|
@ -0,0 +1,58 @@
|
|||
|
||||
# Available settings
|
||||
|
||||
All library settings are handled from a global `COMPONENTS` variable that is read from settings.py. By default you don't need it set, there are reasonable defaults.
|
||||
|
||||
## Configure the module where components are loaded from
|
||||
|
||||
Configure the location where components are loaded. To do this, add a `COMPONENTS` variable to you settings.py with a list of python paths to load. This allows you to build a structure of components that are independent from your apps.
|
||||
|
||||
```python
|
||||
COMPONENTS = {
|
||||
"libraries": [
|
||||
"mysite.components.forms",
|
||||
"mysite.components.buttons",
|
||||
"mysite.components.cards",
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Disable autodiscovery
|
||||
|
||||
If you specify all the component locations with the setting above and have a lot of apps, you can (very) slightly speed things up by disabling autodiscovery.
|
||||
|
||||
```python
|
||||
COMPONENTS = {
|
||||
"autodiscover": False,
|
||||
}
|
||||
```
|
||||
|
||||
## Tune the template cache
|
||||
|
||||
Each time a template is rendered it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up. By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the `template` method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size to `None`.
|
||||
|
||||
```python
|
||||
COMPONENTS = {
|
||||
"template_cache_size": 256,
|
||||
}
|
||||
```
|
||||
|
||||
## Isolate components' context by default
|
||||
|
||||
If you'd like to prevent components from accessing the outer context by default, you can set the `context_behavior` setting to `isolated`. This is useful if you want to make sure that components don't accidentally access the outer context.
|
||||
|
||||
```python
|
||||
COMPONENTS = {
|
||||
"context_behavior": "isolated",
|
||||
}
|
||||
```
|
||||
|
||||
## Middleware
|
||||
|
||||
RENDER_DEPENDENCIES: If you are using the `ComponentDependencyMiddleware` middleware, you can enable or disable it here.
|
||||
|
||||
```python
|
||||
COMPONENTS = {
|
||||
"RENDER_DEPENDENCIES": True,
|
||||
}
|
||||
```
|
225
mkdocs.yml
Normal file
225
mkdocs.yml
Normal file
|
@ -0,0 +1,225 @@
|
|||
---
|
||||
site_name: Django-Components
|
||||
site_description: A way to create simple reusable template components in Django.
|
||||
site_url: https://emilstenstrom.github.io/django-components/
|
||||
|
||||
repo_url: https://github.com/EmilStenstrom/django-components
|
||||
repo_name: EmilStenstrom/django-components
|
||||
edit_uri: https://github.com/EmilStenstrom/django-components/edit/master/docs/
|
||||
|
||||
dev_addr: "127.0.0.1:9000"
|
||||
site_dir: site
|
||||
docs_dir: docs
|
||||
|
||||
watch:
|
||||
- src
|
||||
- docs
|
||||
- mkdocs.yml
|
||||
- README.md
|
||||
- scripts
|
||||
|
||||
validation:
|
||||
omitted_files: warn
|
||||
absolute_links: warn
|
||||
unrecognized_links: warn
|
||||
|
||||
theme:
|
||||
name: "material"
|
||||
features:
|
||||
- content.action.edit
|
||||
- content.action.view
|
||||
- content.code.annotate
|
||||
- content.code.copy
|
||||
- content.tabs.link
|
||||
- navigation.expand
|
||||
- navigation.footer
|
||||
- navigation.instant
|
||||
- navigation.instant.progress
|
||||
- navigation.indexes
|
||||
- navigation.sections
|
||||
- navigation.tracking
|
||||
- navigation.tabs
|
||||
- navigation.tabs.sticky
|
||||
- navigation.top
|
||||
- search.highlight
|
||||
- search.share
|
||||
- search.suggest
|
||||
- toc.follow
|
||||
icon:
|
||||
repo: fontawesome/brands/github
|
||||
palette:
|
||||
- media: "(prefers-color-scheme)"
|
||||
toggle:
|
||||
icon: material/brightness-auto
|
||||
name: Switch to light mode
|
||||
- media: "(prefers-color-scheme: light)"
|
||||
scheme: default
|
||||
primary: teal
|
||||
toggle:
|
||||
icon: material/weather-night
|
||||
name: Switch to dark mode
|
||||
- media: "(prefers-color-scheme: dark)"
|
||||
scheme: slate
|
||||
primary: teal
|
||||
toggle:
|
||||
icon: material/weather-sunny
|
||||
name: Switch to light mode
|
||||
extra:
|
||||
version:
|
||||
provider: mike
|
||||
default:
|
||||
- latest
|
||||
- dev
|
||||
social:
|
||||
- icon: fontawesome/brands/github
|
||||
link: https://github.com/EmilStenstrom/django-components
|
||||
- icon: fontawesome/brands/python
|
||||
link: https://pypi.org/project/django-components/
|
||||
|
||||
nav:
|
||||
- Home:
|
||||
- index.md
|
||||
- Changelog: CHANGELOG.md
|
||||
- Code of Conduct: CODE_OF_CONDUCT.md
|
||||
- License: license.md
|
||||
- Usage: #user_guide/
|
||||
|
||||
# - user_guide/index.md
|
||||
- Installation:
|
||||
- user_guide/installation.md
|
||||
- user_guide/requirements_compatibility.md
|
||||
- user_guide/getting_started.md
|
||||
- user_guide/security.md
|
||||
- Creating & Using Components:
|
||||
- user_guide/creating_using_components/create_first_component.md
|
||||
- user_guide/creating_using_components/use_component.md
|
||||
- user_guide/creating_using_components/single_file_component.md
|
||||
- user_guide/creating_using_components/context_scope.md
|
||||
- user_guide/creating_using_components/using_slots.md
|
||||
- user_guide/creating_using_components/middleware.md
|
||||
- user_guide/creating_using_components/advanced.md
|
||||
- user_guide/settings.md
|
||||
- user_guide/commands.md
|
||||
- user_guide/logging_debugging.md
|
||||
|
||||
|
||||
- Development:
|
||||
- dev_guide/index.md
|
||||
- Reference:
|
||||
- API: reference/
|
||||
|
||||
|
||||
markdown_extensions:
|
||||
abbr: {}
|
||||
admonition: {}
|
||||
attr_list: {}
|
||||
codehilite: {}
|
||||
def_list: {}
|
||||
tables: {}
|
||||
md_in_html: {}
|
||||
mdx_truly_sane_lists: {}
|
||||
pymdownx.magiclink:
|
||||
repo_url_shorthand: true
|
||||
user: EmilStenstrom
|
||||
repo: django-components
|
||||
pymdownx.details: {}
|
||||
pymdownx.highlight:
|
||||
anchor_linenums: true
|
||||
pymdownx.inlinehilite: {}
|
||||
pymdownx.snippets:
|
||||
check_paths: true
|
||||
base_path: .
|
||||
pymdownx.tabbed:
|
||||
alternate_style: true
|
||||
pymdownx.superfences:
|
||||
pymdownx.tasklist:
|
||||
custom_checkbox: true
|
||||
pymdownx.emoji:
|
||||
emoji_index: !!python/name:material.extensions.emoji.twemoji
|
||||
emoji_generator: !!python/name:material.extensions.emoji.to_svg
|
||||
toc:
|
||||
permalink: "¤"
|
||||
|
||||
|
||||
plugins:
|
||||
- autorefs
|
||||
- include-markdown:
|
||||
# Default is django style...
|
||||
opening_tag: "{!"
|
||||
closing_tag: "!}"
|
||||
- gen-files:
|
||||
scripts:
|
||||
- scripts/gen_ref_nav.py
|
||||
- literate-nav
|
||||
- git-revision-date-localized:
|
||||
enabled: !ENV [CI, false]
|
||||
- git-authors:
|
||||
enabled: !ENV [CI, false]
|
||||
- markdown-exec
|
||||
# - toc-md:
|
||||
- search
|
||||
- section-index
|
||||
- social:
|
||||
enabled: !ENV [CI, false]
|
||||
- mike:
|
||||
canonical_version: "latest"
|
||||
version_selector: true
|
||||
- redirects:
|
||||
redirect_maps:
|
||||
# - minify:
|
||||
# minify_html: true
|
||||
- mkdocstrings:
|
||||
handlers:
|
||||
python:
|
||||
import:
|
||||
- https://docs.python.org/3.12/objects.inv
|
||||
- url: https://docs.djangoproject.com/en/5.0/_objects/
|
||||
base_url: https://docs.djangoproject.com/en/5.0/
|
||||
domains: [std, py]
|
||||
paths: [src] # search packages in the src folder
|
||||
options:
|
||||
# docstring_options:
|
||||
# ignore_init_summary: true
|
||||
# docstring_section_style: list
|
||||
# filters: ["!^_"]
|
||||
# heading_level: 1
|
||||
# inherited_members: true
|
||||
# merge_init_into_class: true
|
||||
# preload_modules: [mkdocstrings]
|
||||
# separate_signature: true
|
||||
# show_root_heading: true
|
||||
# show_root_full_path: false
|
||||
# show_signature_annotations: true
|
||||
# show_source: false
|
||||
# show_symbol_type_heading: true
|
||||
# show_symbol_type_toc: true
|
||||
# signature_crossrefs: true
|
||||
# summary: true
|
||||
# unwrap_annotated: true
|
||||
docstring_options:
|
||||
ignore_init_summary: true
|
||||
docstring_section_style: list
|
||||
filters: ["!^_"]
|
||||
heading_level: 1
|
||||
inherited_members: true
|
||||
merge_init_into_class: true
|
||||
preload_modules: [mkdocstrings]
|
||||
separate_signature: true
|
||||
show_root_heading: true
|
||||
show_root_full_path: false
|
||||
show_signature_annotations: true
|
||||
show_symbol_type_heading: true
|
||||
show_symbol_type_toc: true
|
||||
signature_crossrefs: true
|
||||
summary: true
|
||||
unwrap_annotated: true
|
||||
# show_root_heading: true
|
||||
# show_signature_annotations: true
|
||||
show_if_no_docstring: false
|
||||
# separate_signature: true
|
||||
line_length: 140
|
||||
# merge_init_into_class: true
|
||||
show_submodules: true
|
||||
docstring_style: google
|
||||
# docstring_options:
|
||||
# ignore_init_summary: true
|
|
@ -97,3 +97,32 @@ disallow_untyped_defs = true
|
|||
testpaths = [
|
||||
"tests"
|
||||
]
|
||||
|
||||
[tool.hatch.env]
|
||||
requires = [
|
||||
"hatch-mkdocs",
|
||||
"hatch-pip-compile"
|
||||
]
|
||||
|
||||
[tool.hatch.envs.default]
|
||||
dependencies = [
|
||||
"django",
|
||||
"tox",
|
||||
"pytest",
|
||||
"flake8",
|
||||
"flake8-pyproject",
|
||||
"isort",
|
||||
"pre-commit",
|
||||
"black",
|
||||
"mypy",
|
||||
]
|
||||
type = "pip-compile"
|
||||
lock-filename = "requirements-dev.txt"
|
||||
|
||||
[tool.hatch.envs.docs]
|
||||
type = "pip-compile"
|
||||
lock-filename = "requirements-docs.txt"
|
||||
|
||||
[tool.hatch.env.collectors.mkdocs.docs]
|
||||
# Dependencies are fetched automatically from the mkdocs.yml file with hatch-mkdocs
|
||||
path = "mkdocs.yml"
|
||||
|
|
199
requirements-docs.txt
Normal file
199
requirements-docs.txt
Normal file
|
@ -0,0 +1,199 @@
|
|||
#
|
||||
# This file is autogenerated by hatch-pip-compile with Python 3.12
|
||||
#
|
||||
# - markdown-exec
|
||||
# - mdx-truly-sane-lists
|
||||
# - mike
|
||||
# - mkdocs
|
||||
# - mkdocs-autorefs
|
||||
# - mkdocs-gen-files
|
||||
# - mkdocs-git-authors-plugin
|
||||
# - mkdocs-git-revision-date-localized-plugin
|
||||
# - mkdocs-include-markdown-plugin
|
||||
# - mkdocs-literate-nav
|
||||
# - mkdocs-material
|
||||
# - mkdocs-material[imaging]
|
||||
# - mkdocs-redirects
|
||||
# - mkdocs-section-index
|
||||
# - mkdocstrings
|
||||
# - mkdocstrings-python
|
||||
# - pymdown-extensions
|
||||
#
|
||||
|
||||
babel==2.14.0
|
||||
# via
|
||||
# mkdocs-git-revision-date-localized-plugin
|
||||
# mkdocs-material
|
||||
bracex==2.4
|
||||
# via wcmatch
|
||||
cairocffi==1.6.1
|
||||
# via cairosvg
|
||||
cairosvg==2.7.1
|
||||
# via mkdocs-material
|
||||
certifi==2024.2.2
|
||||
# via requests
|
||||
cffi==1.16.0
|
||||
# via cairocffi
|
||||
charset-normalizer==3.3.2
|
||||
# via requests
|
||||
click==8.1.7
|
||||
# via
|
||||
# mkdocs
|
||||
# mkdocstrings
|
||||
colorama==0.4.6
|
||||
# via
|
||||
# griffe
|
||||
# mkdocs-material
|
||||
cssselect2==0.7.0
|
||||
# via cairosvg
|
||||
defusedxml==0.7.1
|
||||
# via cairosvg
|
||||
ghp-import==2.1.0
|
||||
# via mkdocs
|
||||
gitdb==4.0.11
|
||||
# via gitpython
|
||||
gitpython==3.1.43
|
||||
# via mkdocs-git-revision-date-localized-plugin
|
||||
griffe==0.42.1
|
||||
# via mkdocstrings-python
|
||||
idna==3.6
|
||||
# via requests
|
||||
importlib-metadata==7.1.0
|
||||
# via mike
|
||||
importlib-resources==6.4.0
|
||||
# via mike
|
||||
jinja2==3.1.3
|
||||
# via
|
||||
# mike
|
||||
# mkdocs
|
||||
# mkdocs-material
|
||||
# mkdocstrings
|
||||
markdown==3.5.2
|
||||
# via
|
||||
# mdx-truly-sane-lists
|
||||
# mkdocs
|
||||
# mkdocs-autorefs
|
||||
# mkdocs-material
|
||||
# mkdocstrings
|
||||
# mkdocstrings-python
|
||||
# pymdown-extensions
|
||||
markdown-exec==1.8.0
|
||||
# via hatch.envs.docs
|
||||
markupsafe==2.1.5
|
||||
# via
|
||||
# jinja2
|
||||
# mkdocs
|
||||
# mkdocs-autorefs
|
||||
# mkdocstrings
|
||||
mdx-truly-sane-lists==1.3
|
||||
# via hatch.envs.docs
|
||||
mergedeep==1.3.4
|
||||
# via mkdocs
|
||||
mike==2.0.0
|
||||
# via hatch.envs.docs
|
||||
mkdocs==1.5.3
|
||||
# via
|
||||
# hatch.envs.docs
|
||||
# mike
|
||||
# mkdocs-autorefs
|
||||
# mkdocs-gen-files
|
||||
# mkdocs-git-authors-plugin
|
||||
# mkdocs-git-revision-date-localized-plugin
|
||||
# mkdocs-include-markdown-plugin
|
||||
# mkdocs-literate-nav
|
||||
# mkdocs-material
|
||||
# mkdocs-redirects
|
||||
# mkdocs-section-index
|
||||
# mkdocstrings
|
||||
mkdocs-autorefs==1.0.1
|
||||
# via
|
||||
# hatch.envs.docs
|
||||
# mkdocstrings
|
||||
mkdocs-gen-files==0.5.0
|
||||
# via hatch.envs.docs
|
||||
mkdocs-git-authors-plugin==0.8.0
|
||||
# via hatch.envs.docs
|
||||
mkdocs-git-revision-date-localized-plugin==1.2.4
|
||||
# via hatch.envs.docs
|
||||
mkdocs-include-markdown-plugin==6.0.5
|
||||
# via hatch.envs.docs
|
||||
mkdocs-literate-nav==0.6.1
|
||||
# via hatch.envs.docs
|
||||
mkdocs-material==9.5.16
|
||||
# via hatch.envs.docs
|
||||
mkdocs-material-extensions==1.3.1
|
||||
# via mkdocs-material
|
||||
mkdocs-redirects==1.2.1
|
||||
# via hatch.envs.docs
|
||||
mkdocs-section-index==0.3.8
|
||||
# via hatch.envs.docs
|
||||
mkdocstrings==0.24.1
|
||||
# via
|
||||
# hatch.envs.docs
|
||||
# mkdocstrings-python
|
||||
mkdocstrings-python==1.9.0
|
||||
# via hatch.envs.docs
|
||||
packaging==24.0
|
||||
# via mkdocs
|
||||
paginate==0.5.6
|
||||
# via mkdocs-material
|
||||
pathspec==0.12.1
|
||||
# via mkdocs
|
||||
pillow==10.2.0
|
||||
# via
|
||||
# cairosvg
|
||||
# mkdocs-material
|
||||
platformdirs==4.2.0
|
||||
# via
|
||||
# mkdocs
|
||||
# mkdocstrings
|
||||
pycparser==2.22
|
||||
# via cffi
|
||||
pygments==2.17.2
|
||||
# via mkdocs-material
|
||||
pymdown-extensions==10.7.1
|
||||
# via
|
||||
# hatch.envs.docs
|
||||
# markdown-exec
|
||||
# mkdocs-material
|
||||
# mkdocstrings
|
||||
pyparsing==3.1.2
|
||||
# via mike
|
||||
python-dateutil==2.9.0.post0
|
||||
# via ghp-import
|
||||
pytz==2024.1
|
||||
# via mkdocs-git-revision-date-localized-plugin
|
||||
pyyaml==6.0.1
|
||||
# via
|
||||
# mike
|
||||
# mkdocs
|
||||
# pymdown-extensions
|
||||
# pyyaml-env-tag
|
||||
pyyaml-env-tag==0.1
|
||||
# via mkdocs
|
||||
regex==2023.12.25
|
||||
# via mkdocs-material
|
||||
requests==2.31.0
|
||||
# via mkdocs-material
|
||||
six==1.16.0
|
||||
# via python-dateutil
|
||||
smmap==5.0.1
|
||||
# via gitdb
|
||||
tinycss2==1.2.1
|
||||
# via
|
||||
# cairosvg
|
||||
# cssselect2
|
||||
urllib3==2.2.1
|
||||
# via requests
|
||||
verspec==0.1.0
|
||||
# via mike
|
||||
watchdog==4.0.0
|
||||
# via mkdocs
|
||||
wcmatch==8.5.1
|
||||
# via mkdocs-include-markdown-plugin
|
||||
webencodings==0.5.1
|
||||
# via
|
||||
# cssselect2
|
||||
# tinycss2
|
||||
zipp==3.18.1
|
||||
# via importlib-metadata
|
42
scripts/gen_ref_nav.py
Normal file
42
scripts/gen_ref_nav.py
Normal file
|
@ -0,0 +1,42 @@
|
|||
# Adapted from https://github.com/mkdocstrings/python/blob/main/scripts/gen_ref_nav.py
|
||||
# License: ISC License - Copyright (c) 2021, Timothée Mazzucotelli
|
||||
|
||||
"""Generate the code reference pages and navigation.
|
||||
|
||||
No need to run this script manually, it is called by mkdocs-material during the build process.
|
||||
|
||||
You can run it manually to test the output.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import mkdocs_gen_files
|
||||
|
||||
nav = mkdocs_gen_files.Nav()
|
||||
mod_symbol = '<code class="doc-symbol doc-symbol-nav doc-symbol-module"></code>'
|
||||
|
||||
root = Path(__file__).parent.parent
|
||||
src = root / "src"
|
||||
|
||||
for path in sorted(src.rglob("*.py")):
|
||||
module_path = path.relative_to(src).with_suffix("")
|
||||
doc_path = path.relative_to(src).with_suffix(".md")
|
||||
full_doc_path = Path("reference", doc_path)
|
||||
|
||||
parts = tuple(module_path.parts)
|
||||
|
||||
doc_path = doc_path / "index.md"
|
||||
full_doc_path = full_doc_path / "index.md"
|
||||
nav_parts = [f"{mod_symbol} {part}" for part in parts]
|
||||
nav[tuple(nav_parts)] = doc_path.as_posix()
|
||||
if parts[-1] == "__init__":
|
||||
parts = parts[:-1]
|
||||
|
||||
with mkdocs_gen_files.open(full_doc_path, "w") as fd:
|
||||
ident = ".".join(parts)
|
||||
fd.write(f"::: {ident}")
|
||||
|
||||
mkdocs_gen_files.set_edit_path(full_doc_path, ".." / path.relative_to(root))
|
||||
|
||||
with mkdocs_gen_files.open("reference/SUMMARY.md", "w") as nav_file:
|
||||
nav_file.writelines(nav.build_literate_nav())
|
|
@ -1,4 +1,6 @@
|
|||
# flake8: noqa F401
|
||||
"""Main package for Django Components."""
|
||||
|
||||
import django
|
||||
|
||||
# Public API
|
||||
|
|
|
@ -195,10 +195,10 @@ def fill(parser: Parser, token: Token) -> FillNode:
|
|||
def component(parser: Parser, token: Token, tag_name: str) -> ComponentNode:
|
||||
"""
|
||||
To give the component access to the template context:
|
||||
{% component "name" positional_arg keyword_arg=value ... %}
|
||||
```#!htmldjango {% component "name" positional_arg keyword_arg=value ... %}```
|
||||
|
||||
To render the component in an isolated context:
|
||||
{% component "name" positional_arg keyword_arg=value ... only %}
|
||||
```#!htmldjango {% component "name" positional_arg keyword_arg=value ... only %}```
|
||||
|
||||
Positional and keyword arguments can be literals or template variables.
|
||||
The component name must be a single- or double-quotes string and must
|
||||
|
@ -306,7 +306,7 @@ def html_attrs(parser: Parser, token: Token) -> HtmlAttrsNode:
|
|||
will result in `class="my-class extra-class".
|
||||
|
||||
Example:
|
||||
```django
|
||||
```htmldjango
|
||||
{% html_attrs attrs defaults:class="default-class" class="extra-class" data-id="123" %}
|
||||
```
|
||||
"""
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue