chore: init docs

This commit is contained in:
Gabriel Dugny 2024-04-01 14:09:17 +02:00 committed by Emil Stenström
parent 899b9a2738
commit 163b0941c2
49 changed files with 1447 additions and 9 deletions

View 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 %}
```

View 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.

View file

@ -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.
![Directory structure for django_components](https://user-images.githubusercontent.com/224130/179460219-fb51eae1-aab2-4f69-b71f-90cd5ab51bb1.png)
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.

View 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 ...
}
```

View file

@ -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.

View 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.

View 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).