django-components 0.93__tar.gz → 0.94__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. {django_components-0.93/src/django_components.egg-info → django_components-0.94}/PKG-INFO +91 -3
  2. {django_components-0.93 → django_components-0.94}/README.md +90 -2
  3. {django_components-0.93 → django_components-0.94}/pyproject.toml +1 -1
  4. {django_components-0.93 → django_components-0.94}/src/django_components/app_settings.py +8 -0
  5. django_components-0.94/src/django_components/apps.py +45 -0
  6. {django_components-0.93 → django_components-0.94}/src/django_components/templatetags/component_tags.py +29 -31
  7. {django_components-0.93 → django_components-0.94}/src/django_components/utils.py +14 -1
  8. {django_components-0.93 → django_components-0.94/src/django_components.egg-info}/PKG-INFO +91 -3
  9. {django_components-0.93 → django_components-0.94}/tests/test_templatetags.py +32 -1
  10. django_components-0.93/src/django_components/apps.py +0 -17
  11. {django_components-0.93 → django_components-0.94}/LICENSE +0 -0
  12. {django_components-0.93 → django_components-0.94}/setup.cfg +0 -0
  13. {django_components-0.93 → django_components-0.94}/src/django_components/__init__.py +0 -0
  14. {django_components-0.93 → django_components-0.94}/src/django_components/attributes.py +0 -0
  15. {django_components-0.93 → django_components-0.94}/src/django_components/autodiscover.py +0 -0
  16. {django_components-0.93 → django_components-0.94}/src/django_components/component.py +0 -0
  17. {django_components-0.93 → django_components-0.94}/src/django_components/component_media.py +0 -0
  18. {django_components-0.93 → django_components-0.94}/src/django_components/component_registry.py +0 -0
  19. {django_components-0.93 → django_components-0.94}/src/django_components/context.py +0 -0
  20. {django_components-0.93 → django_components-0.94}/src/django_components/expression.py +0 -0
  21. {django_components-0.93 → django_components-0.94}/src/django_components/library.py +0 -0
  22. {django_components-0.93 → django_components-0.94}/src/django_components/logger.py +0 -0
  23. {django_components-0.93 → django_components-0.94}/src/django_components/management/__init__.py +0 -0
  24. {django_components-0.93 → django_components-0.94}/src/django_components/management/commands/__init__.py +0 -0
  25. {django_components-0.93 → django_components-0.94}/src/django_components/management/commands/startcomponent.py +0 -0
  26. {django_components-0.93 → django_components-0.94}/src/django_components/management/commands/upgradecomponent.py +0 -0
  27. {django_components-0.93 → django_components-0.94}/src/django_components/middleware.py +0 -0
  28. {django_components-0.93 → django_components-0.94}/src/django_components/node.py +0 -0
  29. {django_components-0.93 → django_components-0.94}/src/django_components/provide.py +0 -0
  30. {django_components-0.93 → django_components-0.94}/src/django_components/py.typed +0 -0
  31. {django_components-0.93 → django_components-0.94}/src/django_components/safer_staticfiles/__init__.py +0 -0
  32. {django_components-0.93 → django_components-0.94}/src/django_components/safer_staticfiles/apps.py +0 -0
  33. {django_components-0.93 → django_components-0.94}/src/django_components/slots.py +0 -0
  34. {django_components-0.93 → django_components-0.94}/src/django_components/tag_formatter.py +0 -0
  35. {django_components-0.93 → django_components-0.94}/src/django_components/template_loader.py +0 -0
  36. {django_components-0.93 → django_components-0.94}/src/django_components/template_parser.py +0 -0
  37. {django_components-0.93 → django_components-0.94}/src/django_components/templatetags/__init__.py +0 -0
  38. {django_components-0.93 → django_components-0.94}/src/django_components/types.py +0 -0
  39. {django_components-0.93 → django_components-0.94}/src/django_components.egg-info/SOURCES.txt +0 -0
  40. {django_components-0.93 → django_components-0.94}/src/django_components.egg-info/dependency_links.txt +0 -0
  41. {django_components-0.93 → django_components-0.94}/src/django_components.egg-info/requires.txt +0 -0
  42. {django_components-0.93 → django_components-0.94}/src/django_components.egg-info/top_level.txt +0 -0
  43. {django_components-0.93 → django_components-0.94}/tests/test_attributes.py +0 -0
  44. {django_components-0.93 → django_components-0.94}/tests/test_autodiscover.py +0 -0
  45. {django_components-0.93 → django_components-0.94}/tests/test_command_startcomponent.py +0 -0
  46. {django_components-0.93 → django_components-0.94}/tests/test_component.py +0 -0
  47. {django_components-0.93 → django_components-0.94}/tests/test_component_as_view.py +0 -0
  48. {django_components-0.93 → django_components-0.94}/tests/test_component_media.py +0 -0
  49. {django_components-0.93 → django_components-0.94}/tests/test_context.py +0 -0
  50. {django_components-0.93 → django_components-0.94}/tests/test_dependency_rendering.py +0 -0
  51. {django_components-0.93 → django_components-0.94}/tests/test_expression.py +0 -0
  52. {django_components-0.93 → django_components-0.94}/tests/test_registry.py +0 -0
  53. {django_components-0.93 → django_components-0.94}/tests/test_safer_staticfiles.py +0 -0
  54. {django_components-0.93 → django_components-0.94}/tests/test_settings.py +0 -0
  55. {django_components-0.93 → django_components-0.94}/tests/test_tag_formatter.py +0 -0
  56. {django_components-0.93 → django_components-0.94}/tests/test_template_loader.py +0 -0
  57. {django_components-0.93 → django_components-0.94}/tests/test_template_parser.py +0 -0
  58. {django_components-0.93 → django_components-0.94}/tests/test_templatetags_component.py +0 -0
  59. {django_components-0.93 → django_components-0.94}/tests/test_templatetags_provide.py +0 -0
  60. {django_components-0.93 → django_components-0.94}/tests/test_templatetags_slot_fill.py +0 -0
  61. {django_components-0.93 → django_components-0.94}/tests/test_templatetags_templating.py +0 -0
  62. {django_components-0.93 → django_components-0.94}/tests/test_utils.py +0 -0
  63. {django_components-0.93 → django_components-0.94}/tests/testutils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.93
3
+ Version: 0.94
4
4
  Summary: A way to create simple reusable template components in Django.
5
5
  Author-email: Emil Stenström <emil@emilstenstrom.se>
6
6
  License: MIT
@@ -81,6 +81,7 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
81
81
  - [Defining HTML/JS/CSS files](#defining-htmljscss-files)
82
82
  - [Rendering JS/CSS dependencies](#rendering-jscss-dependencies)
83
83
  - [Available settings](#available-settings)
84
+ - [Running with development server](#running-with-development-server)
84
85
  - [Logging and debugging](#logging-and-debugging)
85
86
  - [Management Command](#management-command)
86
87
  - [Writing and sharing component libraries](#writing-and-sharing-component-libraries)
@@ -90,9 +91,13 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
90
91
 
91
92
  ## Release notes
92
93
 
94
+ **Version 0.94**
95
+ - django_components now automatically configures Django to support multi-line tags. (See [Multi-line tags](#multi-line-tags))
96
+ - New setting `reload_on_template_change`. Set this to `True` to reload the dev server on changes to component template files. (See [Reload dev server on component file changes](#reload-dev-server-on-component-file-changes))
97
+
93
98
  **Version 0.93**
94
- - Spread operator `...dict` inside template tags. See [Spread operator](#spread-operator))
95
- - Use template tags inside string literals in component inputs. See [Use template tags inside component inputs](#use-template-tags-inside-component-inputs))
99
+ - Spread operator `...dict` inside template tags. (See [Spread operator](#spread-operator))
100
+ - Use template tags inside string literals in component inputs. (See [Use template tags inside component inputs](#use-template-tags-inside-component-inputs))
96
101
  - Dynamic slots, fills and provides - The `name` argument for these can now be a variable, a template expression, or via spread operator
97
102
  - Component library authors can now configure `CONTEXT_BEHAVIOR` and `TAG_FORMATTER` settings independently from user settings.
98
103
 
@@ -251,6 +256,7 @@ For a step-by-step guide on deploying production server with static files,
251
256
  4. Modify `TEMPLATES` section of settings.py as follows:
252
257
 
253
258
  - _Remove `'APP_DIRS': True,`_
259
+ - NOTE: Instead of APP_DIRS, for the same effect, we will use [`django.template.loaders.app_directories.Loader`](https://docs.djangoproject.com/en/5.1/ref/templates/api/#django.template.loaders.app_directories.Loader)
254
260
  - Add `loaders` to `OPTIONS` list and set it to following value:
255
261
 
256
262
  ```python
@@ -263,8 +269,11 @@ For a step-by-step guide on deploying production server with static files,
263
269
  ],
264
270
  'loaders':[(
265
271
  'django.template.loaders.cached.Loader', [
272
+ # Default Django loader
266
273
  'django.template.loaders.filesystem.Loader',
274
+ # Inluding this is the same as APP_DIRS=True
267
275
  'django.template.loaders.app_directories.Loader',
276
+ # Components loader
268
277
  'django_components.template_loader.Loader',
269
278
  ]
270
279
  )],
@@ -2233,6 +2242,34 @@ Sweet! Now all the relevant HTML is inside the template, and we can move it to a
2233
2242
  > {"attrs": {"my_key:two": 2}}
2234
2243
  > ```
2235
2244
 
2245
+ ### Multi-line tags
2246
+
2247
+ By default, Django expects a template tag to be defined on a single line.
2248
+
2249
+ However, this can become unwieldy if you have a component with a lot of inputs:
2250
+
2251
+ ```django
2252
+ {% component "card" title="Joanne Arc" subtitle="Head of Kitty Relations" date_last_active="2024-09-03" ... %}
2253
+ ```
2254
+
2255
+ Instead, when you install django_components, it automatically configures Django
2256
+ to suport multi-line tags.
2257
+
2258
+ So we can rewrite the above as:
2259
+
2260
+ ```django
2261
+ {% component "card"
2262
+ title="Joanne Arc"
2263
+ subtitle="Head of Kitty Relations"
2264
+ date_last_active="2024-09-03"
2265
+ ...
2266
+ %}
2267
+ ```
2268
+
2269
+ Much better!
2270
+
2271
+ To disable this behavior, set [`COMPONENTS.multiline_tag`](#multiline_tags---enabledisable-multiline-support) to `False`
2272
+
2236
2273
  ## Prop drilling and dependency injection (provide / inject)
2237
2274
 
2238
2275
  _New in version 0.80_:
@@ -2773,6 +2810,20 @@ COMPONENTS = {
2773
2810
 
2774
2811
  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 resonable defaults.
2775
2812
 
2813
+ Here's overview of all available settings and their defaults:
2814
+
2815
+ ```py
2816
+ COMPONENTS = {
2817
+ "autodiscover": True,
2818
+ "context_behavior": "django", # "django" | "isolated"
2819
+ "libraries": [], # ["mysite.components.forms", ...]
2820
+ "multiline_tags": True,
2821
+ "reload_on_template_change": False,
2822
+ "tag_formatter": "django_components.component_formatter",
2823
+ "template_cache_size": 128,
2824
+ }
2825
+ ```
2826
+
2776
2827
  ### `libraries` - Load component modules
2777
2828
 
2778
2829
  Configure the locations 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.
@@ -2825,6 +2876,16 @@ COMPONENTS = {
2825
2876
  }
2826
2877
  ```
2827
2878
 
2879
+ ### `multiline_tags` - Enable/Disable multiline support
2880
+
2881
+ If `True`, template tags can span multiple lines. Default: `True`
2882
+
2883
+ ```python
2884
+ COMPONENTS = {
2885
+ "multiline_tags": True,
2886
+ }
2887
+ ```
2888
+
2828
2889
  ### `template_cache_size` - Tune the template cache
2829
2890
 
2830
2891
  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.
@@ -2942,6 +3003,13 @@ But since `"cheese"` is not defined there, it's empty.
2942
3003
 
2943
3004
  Notice that the variables defined with the `{% with %}` tag are ignored inside the `{% fill %}` tag with the `"isolated"` mode.
2944
3005
 
3006
+ ### `reload_on_template_change` - Reload dev server on component file changes
3007
+
3008
+ If `True`, configures Django to reload on component files. See
3009
+ [Reload dev server on component file changes](#reload-dev-server-on-component-file-changes).
3010
+
3011
+ NOTE: This setting should be enabled only for the dev environment!
3012
+
2945
3013
  ### `tag_formatter` - Change how components are used in templates
2946
3014
  Sets the [`TagFormatter`](#available-tagformatters) instance. See the section [Customizing component tags with TagFormatter](#customizing-component-tags-with-tagformatter).
2947
3015
 
@@ -2963,6 +3031,26 @@ COMPONENTS = {
2963
3031
  }
2964
3032
  ```
2965
3033
 
3034
+ ## Running with development server
3035
+
3036
+ ### Reload dev server on component file changes
3037
+
3038
+ This is relevant if you are using the project structure as shown in our examples, where
3039
+ HTML, JS, CSS and Python are separate and nested in a directory.
3040
+
3041
+ In this case you may notice that when you are running a development server,
3042
+ the server sometimes does not reload when you change comoponent files.
3043
+
3044
+ From relevant [StackOverflow thread](https://stackoverflow.com/a/76722393/9788634):
3045
+
3046
+ > TL;DR is that the server won't reload if it thinks the changed file is in a templates directory,
3047
+ > or in a nested sub directory of a templates directory. This is by design.
3048
+
3049
+ To make the dev server reload on all component files, set [`reload_on_template_change`](#reload_on_template_change---reload-dev-server-on-component-file-changes) to `True`.
3050
+ This configures Django to watch for component files too.
3051
+
3052
+ NOTE: This setting should be enabled only for the dev environment!
3053
+
2966
3054
  ## Logging and debugging
2967
3055
 
2968
3056
  Django components supports [logging with Django](https://docs.djangoproject.com/en/5.0/howto/logging/#logging-how-to). This can help with troubleshooting.
@@ -57,6 +57,7 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
57
57
  - [Defining HTML/JS/CSS files](#defining-htmljscss-files)
58
58
  - [Rendering JS/CSS dependencies](#rendering-jscss-dependencies)
59
59
  - [Available settings](#available-settings)
60
+ - [Running with development server](#running-with-development-server)
60
61
  - [Logging and debugging](#logging-and-debugging)
61
62
  - [Management Command](#management-command)
62
63
  - [Writing and sharing component libraries](#writing-and-sharing-component-libraries)
@@ -66,9 +67,13 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
66
67
 
67
68
  ## Release notes
68
69
 
70
+ **Version 0.94**
71
+ - django_components now automatically configures Django to support multi-line tags. (See [Multi-line tags](#multi-line-tags))
72
+ - New setting `reload_on_template_change`. Set this to `True` to reload the dev server on changes to component template files. (See [Reload dev server on component file changes](#reload-dev-server-on-component-file-changes))
73
+
69
74
  **Version 0.93**
70
- - Spread operator `...dict` inside template tags. See [Spread operator](#spread-operator))
71
- - Use template tags inside string literals in component inputs. See [Use template tags inside component inputs](#use-template-tags-inside-component-inputs))
75
+ - Spread operator `...dict` inside template tags. (See [Spread operator](#spread-operator))
76
+ - Use template tags inside string literals in component inputs. (See [Use template tags inside component inputs](#use-template-tags-inside-component-inputs))
72
77
  - Dynamic slots, fills and provides - The `name` argument for these can now be a variable, a template expression, or via spread operator
73
78
  - Component library authors can now configure `CONTEXT_BEHAVIOR` and `TAG_FORMATTER` settings independently from user settings.
74
79
 
@@ -227,6 +232,7 @@ For a step-by-step guide on deploying production server with static files,
227
232
  4. Modify `TEMPLATES` section of settings.py as follows:
228
233
 
229
234
  - _Remove `'APP_DIRS': True,`_
235
+ - NOTE: Instead of APP_DIRS, for the same effect, we will use [`django.template.loaders.app_directories.Loader`](https://docs.djangoproject.com/en/5.1/ref/templates/api/#django.template.loaders.app_directories.Loader)
230
236
  - Add `loaders` to `OPTIONS` list and set it to following value:
231
237
 
232
238
  ```python
@@ -239,8 +245,11 @@ For a step-by-step guide on deploying production server with static files,
239
245
  ],
240
246
  'loaders':[(
241
247
  'django.template.loaders.cached.Loader', [
248
+ # Default Django loader
242
249
  'django.template.loaders.filesystem.Loader',
250
+ # Inluding this is the same as APP_DIRS=True
243
251
  'django.template.loaders.app_directories.Loader',
252
+ # Components loader
244
253
  'django_components.template_loader.Loader',
245
254
  ]
246
255
  )],
@@ -2209,6 +2218,34 @@ Sweet! Now all the relevant HTML is inside the template, and we can move it to a
2209
2218
  > {"attrs": {"my_key:two": 2}}
2210
2219
  > ```
2211
2220
 
2221
+ ### Multi-line tags
2222
+
2223
+ By default, Django expects a template tag to be defined on a single line.
2224
+
2225
+ However, this can become unwieldy if you have a component with a lot of inputs:
2226
+
2227
+ ```django
2228
+ {% component "card" title="Joanne Arc" subtitle="Head of Kitty Relations" date_last_active="2024-09-03" ... %}
2229
+ ```
2230
+
2231
+ Instead, when you install django_components, it automatically configures Django
2232
+ to suport multi-line tags.
2233
+
2234
+ So we can rewrite the above as:
2235
+
2236
+ ```django
2237
+ {% component "card"
2238
+ title="Joanne Arc"
2239
+ subtitle="Head of Kitty Relations"
2240
+ date_last_active="2024-09-03"
2241
+ ...
2242
+ %}
2243
+ ```
2244
+
2245
+ Much better!
2246
+
2247
+ To disable this behavior, set [`COMPONENTS.multiline_tag`](#multiline_tags---enabledisable-multiline-support) to `False`
2248
+
2212
2249
  ## Prop drilling and dependency injection (provide / inject)
2213
2250
 
2214
2251
  _New in version 0.80_:
@@ -2749,6 +2786,20 @@ COMPONENTS = {
2749
2786
 
2750
2787
  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 resonable defaults.
2751
2788
 
2789
+ Here's overview of all available settings and their defaults:
2790
+
2791
+ ```py
2792
+ COMPONENTS = {
2793
+ "autodiscover": True,
2794
+ "context_behavior": "django", # "django" | "isolated"
2795
+ "libraries": [], # ["mysite.components.forms", ...]
2796
+ "multiline_tags": True,
2797
+ "reload_on_template_change": False,
2798
+ "tag_formatter": "django_components.component_formatter",
2799
+ "template_cache_size": 128,
2800
+ }
2801
+ ```
2802
+
2752
2803
  ### `libraries` - Load component modules
2753
2804
 
2754
2805
  Configure the locations 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.
@@ -2801,6 +2852,16 @@ COMPONENTS = {
2801
2852
  }
2802
2853
  ```
2803
2854
 
2855
+ ### `multiline_tags` - Enable/Disable multiline support
2856
+
2857
+ If `True`, template tags can span multiple lines. Default: `True`
2858
+
2859
+ ```python
2860
+ COMPONENTS = {
2861
+ "multiline_tags": True,
2862
+ }
2863
+ ```
2864
+
2804
2865
  ### `template_cache_size` - Tune the template cache
2805
2866
 
2806
2867
  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.
@@ -2918,6 +2979,13 @@ But since `"cheese"` is not defined there, it's empty.
2918
2979
 
2919
2980
  Notice that the variables defined with the `{% with %}` tag are ignored inside the `{% fill %}` tag with the `"isolated"` mode.
2920
2981
 
2982
+ ### `reload_on_template_change` - Reload dev server on component file changes
2983
+
2984
+ If `True`, configures Django to reload on component files. See
2985
+ [Reload dev server on component file changes](#reload-dev-server-on-component-file-changes).
2986
+
2987
+ NOTE: This setting should be enabled only for the dev environment!
2988
+
2921
2989
  ### `tag_formatter` - Change how components are used in templates
2922
2990
  Sets the [`TagFormatter`](#available-tagformatters) instance. See the section [Customizing component tags with TagFormatter](#customizing-component-tags-with-tagformatter).
2923
2991
 
@@ -2939,6 +3007,26 @@ COMPONENTS = {
2939
3007
  }
2940
3008
  ```
2941
3009
 
3010
+ ## Running with development server
3011
+
3012
+ ### Reload dev server on component file changes
3013
+
3014
+ This is relevant if you are using the project structure as shown in our examples, where
3015
+ HTML, JS, CSS and Python are separate and nested in a directory.
3016
+
3017
+ In this case you may notice that when you are running a development server,
3018
+ the server sometimes does not reload when you change comoponent files.
3019
+
3020
+ From relevant [StackOverflow thread](https://stackoverflow.com/a/76722393/9788634):
3021
+
3022
+ > TL;DR is that the server won't reload if it thinks the changed file is in a templates directory,
3023
+ > or in a nested sub directory of a templates directory. This is by design.
3024
+
3025
+ To make the dev server reload on all component files, set [`reload_on_template_change`](#reload_on_template_change---reload-dev-server-on-component-file-changes) to `True`.
3026
+ This configures Django to watch for component files too.
3027
+
3028
+ NOTE: This setting should be enabled only for the dev environment!
3029
+
2942
3030
  ## Logging and debugging
2943
3031
 
2944
3032
  Django components supports [logging with Django](https://docs.djangoproject.com/en/5.0/howto/logging/#logging-how-to). This can help with troubleshooting.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "django_components"
7
- version = "0.93"
7
+ version = "0.94"
8
8
  requires-python = ">=3.8, <4.0"
9
9
  description = "A way to create simple reusable template components in Django."
10
10
  keywords = ["django", "components", "css", "js", "html"]
@@ -102,6 +102,14 @@ class AppSettings:
102
102
  def LIBRARIES(self) -> List:
103
103
  return self.settings.get("libraries", [])
104
104
 
105
+ @property
106
+ def MULTILINE_TAGS(self) -> bool:
107
+ return self.settings.get("multiline_tags", True)
108
+
109
+ @property
110
+ def RELOAD_ON_TEMPLATE_CHANGE(self) -> bool:
111
+ return self.settings.get("reload_on_template_change", False)
112
+
105
113
  @property
106
114
  def TEMPLATE_CACHE_SIZE(self) -> int:
107
115
  return self.settings.get("template_cache_size", 128)
@@ -0,0 +1,45 @@
1
+ import re
2
+
3
+ from django.apps import AppConfig
4
+
5
+
6
+ class ComponentsConfig(AppConfig):
7
+ name = "django_components"
8
+
9
+ # This is the code that gets run when user adds django_components
10
+ # to Django's INSTALLED_APPS
11
+ def ready(self) -> None:
12
+ from django_components.app_settings import app_settings
13
+ from django_components.autodiscover import autodiscover, get_dirs, import_libraries, search_dirs
14
+ from django_components.utils import watch_files_for_autoreload
15
+
16
+ # Import modules set in `COMPONENTS.libraries` setting
17
+ import_libraries()
18
+
19
+ if app_settings.AUTODISCOVER:
20
+ autodiscover()
21
+
22
+ # Watch template files for changes, so Django dev server auto-reloads
23
+ # See https://github.com/EmilStenstrom/django-components/discussions/567#discussioncomment-10273632
24
+ # And https://stackoverflow.com/questions/42907285/66673186#66673186
25
+ if app_settings.RELOAD_ON_TEMPLATE_CHANGE:
26
+ dirs = get_dirs()
27
+ component_filepaths = search_dirs(dirs, "**/*")
28
+ watch_files_for_autoreload(component_filepaths)
29
+
30
+ if app_settings.MULTILINE_TAGS:
31
+ # Allow tags to span multiple lines. This makes it easier to work with
32
+ # components inside Django templates, allowing us syntax like:
33
+ # ```html
34
+ # {% component "icon"
35
+ # icon='outline_chevron_down'
36
+ # size=16
37
+ # color="text-gray-400"
38
+ # attrs:class="ml-2"
39
+ # %}{% endcomponent %}
40
+ # ```
41
+ #
42
+ # See https://stackoverflow.com/a/54206609/9788634
43
+ from django.template import base
44
+
45
+ base.tag_re = re.compile(base.tag_re.pattern, re.DOTALL)
@@ -232,7 +232,8 @@ def component(parser: Parser, token: Token, registry: ComponentRegistry, tag_nam
232
232
  tag_name,
233
233
  parser,
234
234
  token,
235
- params=True, # Allow many args
235
+ params=[],
236
+ extra_params=True, # Allow many args
236
237
  flags=[COMP_ONLY_FLAG],
237
238
  keywordonly_kwargs=True,
238
239
  repeatable_kwargs=False,
@@ -360,7 +361,8 @@ def _parse_tag(
360
361
  tag: str,
361
362
  parser: Parser,
362
363
  token: Token,
363
- params: Union[List[str], bool] = False,
364
+ params: Optional[List[str]] = None,
365
+ extra_params: bool = False,
364
366
  flags: Optional[List[str]] = None,
365
367
  end_tag: Optional[str] = None,
366
368
  optional_params: Optional[List[str]] = None,
@@ -455,37 +457,36 @@ def _parse_tag(
455
457
  # modify it much to maintain some sort of compatibility with Django's version of
456
458
  # `parse_bits`.
457
459
  # Ideally, Django's parser would be expanded to support our use cases.
458
- if params != True: # noqa F712
459
- params_to_sort = [param for param in params if param not in seen_kwargs]
460
- new_args = []
461
- new_params = []
462
- new_kwargs = []
463
- for index, bit in enumerate(bits):
464
- if is_kwarg(bit) or not len(params_to_sort):
465
- # Pass all remaining bits (including current one) as kwargs
466
- new_kwargs.extend(bits[index:])
467
- break
468
-
469
- param = params_to_sort.pop(0)
470
- if optional_params and param in optional_params:
471
- mark_kwarg_key(param, False)
472
- new_kwargs.append(f"{param}={bit}")
473
- continue
474
- new_args.append(bit)
475
- new_params.append(param)
460
+ params_to_sort = [param for param in params if param not in seen_kwargs]
461
+ new_args = []
462
+ new_params = []
463
+ new_kwargs = []
464
+ for index, bit in enumerate(bits):
465
+ if is_kwarg(bit) or not len(params_to_sort):
466
+ # Pass all remaining bits (including current one) as kwargs
467
+ new_kwargs.extend(bits[index:])
468
+ break
476
469
 
477
- bits = [*new_args, *new_kwargs]
478
- params = [*new_params, *params_to_sort]
470
+ param = params_to_sort.pop(0)
471
+ if optional_params and param in optional_params:
472
+ mark_kwarg_key(param, False)
473
+ new_kwargs.append(f"{param}={bit}")
474
+ continue
475
+ new_args.append(bit)
476
+ new_params.append(param)
479
477
 
480
- # Remove any remaining optional positional args if they were not given
481
- if optional_params:
482
- params = [param for param in params_to_sort if param not in optional_params]
478
+ bits = [*new_args, *new_kwargs]
479
+ params = [*new_params, *params_to_sort]
480
+
481
+ # Remove any remaining optional positional args if they were not given
482
+ if optional_params:
483
+ params = [param for param in params_to_sort if param not in optional_params]
483
484
 
484
485
  # Parse args/kwargs that will be passed to the fill
485
486
  raw_args, raw_kwarg_pairs = parse_bits(
486
487
  parser=parser,
487
488
  bits=bits,
488
- params=[] if isinstance(params, bool) else params,
489
+ params=[] if extra_params else params,
489
490
  name=tag_name,
490
491
  )
491
492
 
@@ -516,14 +517,11 @@ def _parse_tag(
516
517
  kwarg_pairs.append((key, val))
517
518
 
518
519
  # Allow only as many positional args as given
519
- if params != True and len(args) > len(params): # noqa F712
520
+ if not extra_params and len(args) > len(params): # noqa F712
520
521
  raise TemplateSyntaxError(f"Tag '{tag_name}' received unexpected positional arguments: {args[len(params):]}")
521
522
 
522
523
  # For convenience, allow to access named args by their name instead of index
523
- if params != True: # noqa F712
524
- named_args = {param: args[index] for index, param in enumerate(params)}
525
- else:
526
- named_args = {}
524
+ named_args = {param: args[index] for index, param in enumerate(params)}
527
525
 
528
526
  # Validate kwargs
529
527
  kwargs: RuntimeKwargsInput = {}
@@ -1,4 +1,7 @@
1
- from typing import Any, Callable, List
1
+ from pathlib import Path
2
+ from typing import Any, Callable, List, Sequence, Union
3
+
4
+ from django.utils.autoreload import autoreload_started
2
5
 
3
6
  # Global counter to ensure that all IDs generated by `gen_id` WILL be unique
4
7
  _id = 0
@@ -23,3 +26,13 @@ def find_last_index(lst: List, predicate: Callable[[Any], bool]) -> Any:
23
26
 
24
27
  def is_str_wrapped_in_quotes(s: str) -> bool:
25
28
  return s.startswith(('"', "'")) and s[0] == s[-1] and len(s) >= 2
29
+
30
+
31
+ # See https://github.com/EmilStenstrom/django-components/issues/586#issue-2472678136
32
+ def watch_files_for_autoreload(watch_list: Sequence[Union[str, Path]]) -> None:
33
+ def autoreload_hook(sender: Any, *args: Any, **kwargs: Any) -> None:
34
+ watch = sender.extra_files.add
35
+ for file in watch_list:
36
+ watch(Path(file))
37
+
38
+ autoreload_started.connect(autoreload_hook)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.93
3
+ Version: 0.94
4
4
  Summary: A way to create simple reusable template components in Django.
5
5
  Author-email: Emil Stenström <emil@emilstenstrom.se>
6
6
  License: MIT
@@ -81,6 +81,7 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
81
81
  - [Defining HTML/JS/CSS files](#defining-htmljscss-files)
82
82
  - [Rendering JS/CSS dependencies](#rendering-jscss-dependencies)
83
83
  - [Available settings](#available-settings)
84
+ - [Running with development server](#running-with-development-server)
84
85
  - [Logging and debugging](#logging-and-debugging)
85
86
  - [Management Command](#management-command)
86
87
  - [Writing and sharing component libraries](#writing-and-sharing-component-libraries)
@@ -90,9 +91,13 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
90
91
 
91
92
  ## Release notes
92
93
 
94
+ **Version 0.94**
95
+ - django_components now automatically configures Django to support multi-line tags. (See [Multi-line tags](#multi-line-tags))
96
+ - New setting `reload_on_template_change`. Set this to `True` to reload the dev server on changes to component template files. (See [Reload dev server on component file changes](#reload-dev-server-on-component-file-changes))
97
+
93
98
  **Version 0.93**
94
- - Spread operator `...dict` inside template tags. See [Spread operator](#spread-operator))
95
- - Use template tags inside string literals in component inputs. See [Use template tags inside component inputs](#use-template-tags-inside-component-inputs))
99
+ - Spread operator `...dict` inside template tags. (See [Spread operator](#spread-operator))
100
+ - Use template tags inside string literals in component inputs. (See [Use template tags inside component inputs](#use-template-tags-inside-component-inputs))
96
101
  - Dynamic slots, fills and provides - The `name` argument for these can now be a variable, a template expression, or via spread operator
97
102
  - Component library authors can now configure `CONTEXT_BEHAVIOR` and `TAG_FORMATTER` settings independently from user settings.
98
103
 
@@ -251,6 +256,7 @@ For a step-by-step guide on deploying production server with static files,
251
256
  4. Modify `TEMPLATES` section of settings.py as follows:
252
257
 
253
258
  - _Remove `'APP_DIRS': True,`_
259
+ - NOTE: Instead of APP_DIRS, for the same effect, we will use [`django.template.loaders.app_directories.Loader`](https://docs.djangoproject.com/en/5.1/ref/templates/api/#django.template.loaders.app_directories.Loader)
254
260
  - Add `loaders` to `OPTIONS` list and set it to following value:
255
261
 
256
262
  ```python
@@ -263,8 +269,11 @@ For a step-by-step guide on deploying production server with static files,
263
269
  ],
264
270
  'loaders':[(
265
271
  'django.template.loaders.cached.Loader', [
272
+ # Default Django loader
266
273
  'django.template.loaders.filesystem.Loader',
274
+ # Inluding this is the same as APP_DIRS=True
267
275
  'django.template.loaders.app_directories.Loader',
276
+ # Components loader
268
277
  'django_components.template_loader.Loader',
269
278
  ]
270
279
  )],
@@ -2233,6 +2242,34 @@ Sweet! Now all the relevant HTML is inside the template, and we can move it to a
2233
2242
  > {"attrs": {"my_key:two": 2}}
2234
2243
  > ```
2235
2244
 
2245
+ ### Multi-line tags
2246
+
2247
+ By default, Django expects a template tag to be defined on a single line.
2248
+
2249
+ However, this can become unwieldy if you have a component with a lot of inputs:
2250
+
2251
+ ```django
2252
+ {% component "card" title="Joanne Arc" subtitle="Head of Kitty Relations" date_last_active="2024-09-03" ... %}
2253
+ ```
2254
+
2255
+ Instead, when you install django_components, it automatically configures Django
2256
+ to suport multi-line tags.
2257
+
2258
+ So we can rewrite the above as:
2259
+
2260
+ ```django
2261
+ {% component "card"
2262
+ title="Joanne Arc"
2263
+ subtitle="Head of Kitty Relations"
2264
+ date_last_active="2024-09-03"
2265
+ ...
2266
+ %}
2267
+ ```
2268
+
2269
+ Much better!
2270
+
2271
+ To disable this behavior, set [`COMPONENTS.multiline_tag`](#multiline_tags---enabledisable-multiline-support) to `False`
2272
+
2236
2273
  ## Prop drilling and dependency injection (provide / inject)
2237
2274
 
2238
2275
  _New in version 0.80_:
@@ -2773,6 +2810,20 @@ COMPONENTS = {
2773
2810
 
2774
2811
  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 resonable defaults.
2775
2812
 
2813
+ Here's overview of all available settings and their defaults:
2814
+
2815
+ ```py
2816
+ COMPONENTS = {
2817
+ "autodiscover": True,
2818
+ "context_behavior": "django", # "django" | "isolated"
2819
+ "libraries": [], # ["mysite.components.forms", ...]
2820
+ "multiline_tags": True,
2821
+ "reload_on_template_change": False,
2822
+ "tag_formatter": "django_components.component_formatter",
2823
+ "template_cache_size": 128,
2824
+ }
2825
+ ```
2826
+
2776
2827
  ### `libraries` - Load component modules
2777
2828
 
2778
2829
  Configure the locations 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.
@@ -2825,6 +2876,16 @@ COMPONENTS = {
2825
2876
  }
2826
2877
  ```
2827
2878
 
2879
+ ### `multiline_tags` - Enable/Disable multiline support
2880
+
2881
+ If `True`, template tags can span multiple lines. Default: `True`
2882
+
2883
+ ```python
2884
+ COMPONENTS = {
2885
+ "multiline_tags": True,
2886
+ }
2887
+ ```
2888
+
2828
2889
  ### `template_cache_size` - Tune the template cache
2829
2890
 
2830
2891
  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.
@@ -2942,6 +3003,13 @@ But since `"cheese"` is not defined there, it's empty.
2942
3003
 
2943
3004
  Notice that the variables defined with the `{% with %}` tag are ignored inside the `{% fill %}` tag with the `"isolated"` mode.
2944
3005
 
3006
+ ### `reload_on_template_change` - Reload dev server on component file changes
3007
+
3008
+ If `True`, configures Django to reload on component files. See
3009
+ [Reload dev server on component file changes](#reload-dev-server-on-component-file-changes).
3010
+
3011
+ NOTE: This setting should be enabled only for the dev environment!
3012
+
2945
3013
  ### `tag_formatter` - Change how components are used in templates
2946
3014
  Sets the [`TagFormatter`](#available-tagformatters) instance. See the section [Customizing component tags with TagFormatter](#customizing-component-tags-with-tagformatter).
2947
3015
 
@@ -2963,6 +3031,26 @@ COMPONENTS = {
2963
3031
  }
2964
3032
  ```
2965
3033
 
3034
+ ## Running with development server
3035
+
3036
+ ### Reload dev server on component file changes
3037
+
3038
+ This is relevant if you are using the project structure as shown in our examples, where
3039
+ HTML, JS, CSS and Python are separate and nested in a directory.
3040
+
3041
+ In this case you may notice that when you are running a development server,
3042
+ the server sometimes does not reload when you change comoponent files.
3043
+
3044
+ From relevant [StackOverflow thread](https://stackoverflow.com/a/76722393/9788634):
3045
+
3046
+ > TL;DR is that the server won't reload if it thinks the changed file is in a templates directory,
3047
+ > or in a nested sub directory of a templates directory. This is by design.
3048
+
3049
+ To make the dev server reload on all component files, set [`reload_on_template_change`](#reload_on_template_change---reload-dev-server-on-component-file-changes) to `True`.
3050
+ This configures Django to watch for component files too.
3051
+
3052
+ NOTE: This setting should be enabled only for the dev environment!
3053
+
2966
3054
  ## Logging and debugging
2967
3055
 
2968
3056
  Django components supports [logging with Django](https://docs.djangoproject.com/en/5.0/howto/logging/#logging-how-to). This can help with troubleshooting.
@@ -9,7 +9,7 @@ from django_components import Component, register, registry, types
9
9
  from .django_test_setup import setup_test_config
10
10
  from .testutils import BaseTestCase, parametrize_context_behavior
11
11
 
12
- setup_test_config()
12
+ setup_test_config({"autodiscover": False})
13
13
 
14
14
 
15
15
  class SlottedComponent(Component):
@@ -480,3 +480,34 @@ class BlockCompatTests(BaseTestCase):
480
480
  </html>
481
481
  """
482
482
  self.assertHTMLEqual(rendered, expected)
483
+
484
+
485
+ class MultilineTagsTests(BaseTestCase):
486
+ @parametrize_context_behavior(["django", "isolated"])
487
+ def test_multiline_tags(self):
488
+ @register("test_component")
489
+ class SimpleComponent(Component):
490
+ template: types.django_html = """
491
+ Variable: <strong>{{ variable }}</strong>
492
+ """
493
+
494
+ def get_context_data(self, variable, variable2="default"):
495
+ return {
496
+ "variable": variable,
497
+ "variable2": variable2,
498
+ }
499
+
500
+ template: types.django_html = """
501
+ {% load component_tags %}
502
+ {% component
503
+ "test_component"
504
+ 123
505
+ variable2="abc"
506
+ %}
507
+ {% endcomponent %}
508
+ """
509
+ rendered = Template(template).render(Context())
510
+ expected = """
511
+ Variable: <strong>123</strong>
512
+ """
513
+ self.assertHTMLEqual(rendered, expected)
@@ -1,17 +0,0 @@
1
- from django.apps import AppConfig
2
-
3
-
4
- class ComponentsConfig(AppConfig):
5
- name = "django_components"
6
-
7
- # This is the code that gets run when user adds django_components
8
- # to Django's INSTALLED_APPS
9
- def ready(self) -> None:
10
- from django_components.app_settings import app_settings
11
- from django_components.autodiscover import autodiscover, import_libraries
12
-
13
- # Import modules set in `COMPONENTS.libraries` setting
14
- import_libraries()
15
-
16
- if app_settings.AUTODISCOVER:
17
- autodiscover()