Skip to content

Commit

Permalink
Merge pull request #376 from EmilStenstrom/simplify-api
Browse files Browse the repository at this point in the history
Rename component_block to compnent (Fixes #232)
  • Loading branch information
EmilStenstrom committed Feb 26, 2024
2 parents 02ca78a + 58f4644 commit a074d0c
Show file tree
Hide file tree
Showing 34 changed files with 620 additions and 1,039 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ repos:
rev: 7.0.0
hooks:
- id: flake8

additional_dependencies: [flake8-pyproject]
60 changes: 32 additions & 28 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ A way to create simple reusable template components in Django.
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:

```htmldjango
{% component "calendar" date="2015-06-19" %}
{% component "calendar" date="2015-06-19" %}{% endcomponent %}
```

And this is what gets rendered (plus the CSS and Javascript you've specified):
Expand All @@ -20,17 +20,21 @@ Read on to learn about the details!

## Release notes

*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.
<span style="color: red; font-weight: bold">**Version 0.5** CHANGES THE SYNTAX</span> 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.

*Version 0.28* introduces 'implicit' slot filling and the `default` option for `slot` tags.
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.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.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.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 feature to have access to. Hoping that this will feel worth it!
**Version 0.28** introduces 'implicit' slot filling and the `default` option for `slot` tags.

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

## Security notes 🚨

Expand Down Expand Up @@ -220,7 +224,7 @@ First load the `component_tags` tag library, then use the `component_[js/css]_de
{% component_css_dependencies %}
</head>
<body>
{% component "calendar" date="2015-06-19" %}
{% component "calendar" date="2015-06-19" %}{% endcomponent %}
{% component_js_dependencies %}
</body>
<html>
Expand Down Expand Up @@ -297,7 +301,7 @@ 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_block` tag pair.) Fills a declared slot with the specified content.
- `{% 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_.

Expand All @@ -315,9 +319,9 @@ Let's update our calendar component to support more customization. We'll add `sl
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_block "calendar" date="2020-06-06" %}
{% component "calendar" date="2020-06-06" %}
{% fill "body" %}Can you believe it's already <span>{{ date }}</span>??{% endfill %}
{% endcomponent_block %}
{% 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:
Expand All @@ -335,7 +339,7 @@ Since the header block is unspecified, it's taken from the base template. If you

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_block` 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`.
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.

Expand All @@ -355,9 +359,9 @@ The template:
Including the component (notice how the `fill` tag is omitted):

```htmldjango
{% component_block "calendar" date="2020-06-06" %}
{% component "calendar" date="2020-06-06" %}
Can you believe it's already <span>{{ date }}</span>??
{% endcomponent_block %}
{% endcomponent %}
```

The rendered result (exactly the same as before):
Expand All @@ -377,32 +381,32 @@ You may be tempted to combine implicit fills with explicit `fill` tags. This wil

```htmldjango
{# DON'T DO THIS #}
{% component_block "calendar" date="2020-06-06" %}
{% component "calendar" date="2020-06-06" %}
{% fill "header" %}Totally new header!{% endfill %}
Can you believe it's already <span>{{ date }}</span>??
{% endcomponent_block %}
{% endcomponent %}
```

By contrast, it is permitted to use `fill` tags in nested components, e.g.:

```htmldjango
{% component_block "calendar" date="2020-06-06" %}
{% component_block "beautiful-box" %}
{% component "calendar" date="2020-06-06" %}
{% component "beautiful-box" %}
{% fill "content" %} Can you believe it's already <span>{{ date }}</span>?? {% endfill %}
{% endcomponent_block %}
{% endcomponent_block %}
{% endcomponent %}
{% endcomponent %}
```

This is fine too:

```htmldjango
{% component_block "calendar" date="2020-06-06" %}
{% component "calendar" date="2020-06-06" %}
{% fill "header" %}
{% component_block "calendar-header" %}
{% component "calendar-header" %}
Super Special Calendar Header
{% endcomponent_block %}
{% endcomponent %}
{% endfill %}
{% endcomponent_block %}
{% endcomponent %}
```

### Components as views
Expand Down Expand Up @@ -479,9 +483,9 @@ If you're planning on passing an HTML string, check Django's use of [`format_htm
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_block "calendar" date="2020-06-06" %}
{% component "calendar" date="2020-06-06" %}
{% fill "body" as "body" %}{{ body.default }}. Have a great day!{% endfill %}
{% endcomponent_block %}
{% endcomponent %}
```

Produces:
Expand Down Expand Up @@ -614,10 +618,10 @@ COMPONENTS = {

## 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 %}` (or `{% component_block %}` tag):
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 %}
{% 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.
Expand Down
67 changes: 26 additions & 41 deletions benchmarks/component_rendering.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@
from django.test import override_settings

from django_components import component
from django_components.middleware import (
CSS_DEPENDENCY_PLACEHOLDER,
JS_DEPENDENCY_PLACEHOLDER,
)
from django_components.middleware import CSS_DEPENDENCY_PLACEHOLDER, JS_DEPENDENCY_PLACEHOLDER
from tests.django_test_setup import * # NOQA
from tests.testutils import Django30CompatibleSimpleTestCase as SimpleTestCase
from tests.testutils import create_and_process_template_response
Expand Down Expand Up @@ -75,9 +72,7 @@ def setUp(self):
component.registry.clear()
component.registry.register("test_component", SlottedComponent)
component.registry.register("inner_component", SimpleComponent)
component.registry.register(
"breadcrumb_component", BreadcrumbComponent
)
component.registry.register("breadcrumb_component", BreadcrumbComponent)

@staticmethod
def timed_loop(func, iterations=1000):
Expand All @@ -91,22 +86,28 @@ def timed_loop(func, iterations=1000):

def test_render_time_for_small_component(self):
template = Template(
"{% load component_tags %}{% component_block 'test_component' %}"
"{% slot \"header\" %}{% component 'inner_component' variable='foo' %}{% endslot %}"
"{% endcomponent_block %}",
name="root",
"""
{% load component_tags %}
{% component 'test_component' %}
{% slot "header" %}
{% component 'inner_component' variable='foo' %}{% endcomponent %}
{% endslot %}
{% endcomponent %}
"""
)

print(
f"{self.timed_loop(lambda: template.render(Context({})))} ms per iteration"
)
print(f"{self.timed_loop(lambda: template.render(Context({})))} ms per iteration")

def test_middleware_time_with_dependency_for_small_page(self):
template = Template(
"{% load component_tags %}{% component_dependencies %}"
"{% component_block 'test_component' %}{% slot \"header\" %}"
"{% component 'inner_component' variable='foo' %}{% endslot %}{% endcomponent_block %}",
name="root",
"""
{% load component_tags %}{% component_dependencies %}
{% component 'test_component' %}
{% slot "header" %}
{% component 'inner_component' variable='foo' %}{% endcomponent %}
{% endslot %}
{% endcomponent %}
"""
)
# Sanity tests
response_content = create_and_process_template_response(template)
Expand All @@ -116,15 +117,9 @@ def test_middleware_time_with_dependency_for_small_page(self):
self.assertIn("script.js", response_content)

without_middleware = self.timed_loop(
lambda: create_and_process_template_response(
template, use_middleware=False
)
)
with_middleware = self.timed_loop(
lambda: create_and_process_template_response(
template, use_middleware=True
)
lambda: create_and_process_template_response(template, use_middleware=False)
)
with_middleware = self.timed_loop(lambda: create_and_process_template_response(template, use_middleware=True))

print("Small page middleware test")
self.report_results(with_middleware, without_middleware)
Expand All @@ -140,14 +135,10 @@ def test_render_time_with_dependency_for_large_page(self):
self.assertIn("test.js", response_content)

without_middleware = self.timed_loop(
lambda: create_and_process_template_response(
template, {}, use_middleware=False
)
lambda: create_and_process_template_response(template, {}, use_middleware=False)
)
with_middleware = self.timed_loop(
lambda: create_and_process_template_response(
template, {}, use_middleware=True
)
lambda: create_and_process_template_response(template, {}, use_middleware=True)
)

print("Large page middleware test")
Expand All @@ -156,15 +147,9 @@ def test_render_time_with_dependency_for_large_page(self):
@staticmethod
def report_results(with_middleware, without_middleware):
print(f"Middleware active\t\t{with_middleware:.3f} ms per iteration")
print(
f"Middleware inactive\t{without_middleware:.3f} ms per iteration"
)
print(f"Middleware inactive\t{without_middleware:.3f} ms per iteration")
time_difference = with_middleware - without_middleware
if without_middleware > with_middleware:
print(
f"Decrease of {-100 * time_difference / with_middleware:.2f}%"
)
print(f"Decrease of {-100 * time_difference / with_middleware:.2f}%")
else:
print(
f"Increase of {100 * time_difference / without_middleware:.2f}%"
)
print(f"Increase of {100 * time_difference / without_middleware:.2f}%")
8 changes: 2 additions & 6 deletions django_components/app_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,15 @@ def TEMPLATE_CACHE_SIZE(self):

@property
def CONTEXT_BEHAVIOR(self):
raw_value = self.settings.setdefault(
"context_behavior", ContextBehavior.GLOBAL.value
)
raw_value = self.settings.setdefault("context_behavior", ContextBehavior.GLOBAL.value)
return self._validate_context_behavior(raw_value)

def _validate_context_behavior(self, raw_value):
try:
return ContextBehavior(raw_value)
except ValueError:
valid_values = [behavior.value for behavior in ContextBehavior]
raise ValueError(
f"Invalid context behavior: {raw_value}. Valid options are {valid_values}"
)
raise ValueError(f"Invalid context behavior: {raw_value}. Valid options are {valid_values}")


app_settings = AppSettings()
Loading

0 comments on commit a074d0c

Please sign in to comment.