summaryrefslogtreecommitdiffstats
path: root/docs/content/guide/components.md
blob: ac8a77f1069290c44c4c8bbdb2acb87f301a0397 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
---
title: Components
description: Declaring and using components.
---

<Header title="Components">
</Header>

## Declaring and Using Components

The components are simple text files that look like regular Jinja templates, with three requirements:

**First**, components must be placed inside a folder registered in the catalog or a subfolder of it.

```python
catalog.add_folder("myapp/components")
```

You can call that folder whatever you want, not just "components". You can also add more than one folder:

```python
catalog.add_folder("myapp/layouts")
catalog.add_folder("myapp/components")
```

If you end up having more than one component with the same name, the one in the first folder will take priority.

**Second**, they must have a ".jinja" extension. This also helps code editors automatically select the correct language syntax to highlight. However, you can configure it in the catalog.

**Third**, the component name must start with an uppercase letter. Why? This is how JinjaX differentiates a component from a regular HTML tag when using it. I recommend using PascalCase names, like Python classes.

The name of the file (minus the extension) is also how you call the component. For example, if the file is "components/PersonForm.jinja":

```
└ myapp/
  ├── app.py
  ├── components/
        └─ PersonForm.jinja
```

The name of the component is "PersonForm" and can be called like this:

From Python code or a non-component template:

- `catalog.render("PersonForm")`

From another component:

- `<PersonForm> some content </PersonForm>`, or
- `<PersonForm />`

If the component is in a subfolder, the name of that folder becomes part of its name too:

```
└ myapp/
  ├── app.py
  ├── components/
        └─ person
            └─ PersonForm.jinja
```

A "components/person/PersonForm.jinja" component is named "person.PersonForm", meaning the name of the subfolder and the name of the file separated by a dot. This is the full name you use to call it:

From Python code or a non-component template:

- `catalog.render("person.PersonForm")`

From another component:

- `<person.PersonForm> some content </person.PersonForm>`, or
- `<person.PersonForm />`

Notice how the folder name doesn't need to start with an uppercase if you don't want it to.

<a href="/static/img/anatomy-en.png" target="_blank">
  <img src="/static/img/anatomy-en.png" style="margin:0 auto;width:90%;max-width:35rem;">
</a>

## Taking Arguments

More often than not, a component takes one or more arguments to render. Every argument must be declared at the beginning of the component with `{#def arg1, arg2, ... #}`.

```html+jinja
{#def action, method="post", multipart=False #}

<form method="{{ method }}" action="{{ action }}"
  {%- if multipart %} enctype="multipart/form-data"{% endif %}
>
  {{ content }}
</form>
```

In this example, the component takes three arguments: "action", "method", and "multipart". The last two have default values, so they are optional, but the first one doesn't. That means it must be passed a value when rendering the component.

The syntax is exactly like how you declare the arguments of a Python function (in fact, it's parsed by the same code), so it can even include type comments, although they are not used by JinjaX (yet!).

```python
{#def
  data: dict[str, str],
  method: str = "post",
  multipart: bool = False
#}
...
```

## Passing Arguments

There are two types of arguments: strings and expressions.

### String

Strings are passed like regular HTML attributes:

```html+jinja
<Form action="/new" method="PATCH"> ... </Form>

<Alert message="Profile updated" />

<Card title="Hello world" type="big"> ... </Card>
```

### Expressions

There are two different but equivalent ways to pass non-string arguments:

"Jinja-like", where you use double curly braces instead of quotes:

```html+jinja title="Jinja-like"
<Example
    columns={{ 2 }}
    tabbed={{ False }}
    panels={{ {'one': 'lorem', 'two': 'ipsum'} }}
    class={{ 'bg-' + color }}
/>
```

... and "Vue-like", where you keep using quotes, but prefix the name of the attribute with a colon:

```html+jinja title="Vue-like"
<Example
    :columns="2"
    :tabbed="False"
    :panels="{'one': 'lorem', 'two': 'ipsum'}"
    :class="'bg-' + color"
/>
```

<Callout type="note">
  For `True` values, you can just use the name, like in HTML:
  <br>
  ```html+jinja
  <Example class="green" hidden />
  ```
</Callout>

<Callout type="note">
  You can also use dashes when passing an argument, but they will be translated to underscores:
  <br>
  ```html+jinja
  <Example aria-label="Hi" />
  ```
  <br>
  ```html+jinja title="Example.jinja"
  {#def aria_label = "" #}
  ...
  ```
</Callout>

## With Content

There is always an extra implicit argument: **the content** inside the component. Read more about it in the [next](/guide/slots) section.

## Extra Arguments

If you pass arguments not declared in a component, those are not discarded but rather collected in an `attrs` object.

You then call `attrs.render()` to render the received arguments as HTML attributes.

For example, this component:

```html+jinja title="Card.jinja"
{#def title #}
<div {{ attrs.render() }}>
  <h1>{{ title }}</h1>
  {{ content }}
</div>
```

Called as:

```html
<Card title="Products" class="mb-10" open>bla</Card>
```

Will be rendered as:

```html
<div class="mb-10" open>
  <h1>Products</h1>
  bla
</div>
```

You can add or remove arguments before rendering them using the other methods of the `attrs` object. For example:

```html+jinja
{#def title #}
{% do attrs.set(id="mycard") -%}

<div {{ attrs.render() }}>
  <h1>{{ title }}</h1>
  {{ content }}
</div>
```

Or directly in the `attrs.render()` call:

```html+jinja
{#def title #}

<div {{ attrs.render(id="mycard") }}>
  <h1>{{ title }}</h1>
  {{ content }}
</div>
```

<Callout type="info">
The string values passed into components as attrs are not cast to `str` until the string representation is **actually** needed, for example when `attrs.render()` is invoked.
</Callout>

### `attrs` Methods

#### `.render(name=value, ...)`

Renders the attributes and properties as a string.

Any arguments you use with this function are merged with the existing
attibutes/properties by the same rules as the `HTMLAttrs.set()` function:

- Pass a name and a value to set an attribute (e.g. `type="text"`)
- Use `True` as a value to set a property (e.g. `disabled`)
- Use `False` to remove an attribute or property
- The existing attribute/property is overwritten **except** if it is `class`.
  The new classes are appended to the old ones instead of replacing them.
- The underscores in the names will be translated automatically to dashes,
  so `aria_selected` becomes the attribute `aria-selected`.

To provide consistent output, the attributes and properties
are sorted by name and rendered like this:
`<sorted attributes> + <sorted properties>`.

```html+jinja
<Example class="ipsum" width="42" data-good />
```
```html+jinja
<div {{ attrs.render() }}>
<!-- <div class="ipsum" width="42" data-good> -->

<div {{ attrs.render(class="abc", data_good=False, tabindex=0) }}>
<!-- <div class="abc ipsum" width="42" tabindex="0"> -->
```

<Callout type="warning">
Using `<Component {{ attrs.render() }}>` to pass the extra arguments to other components **WILL NOT WORK**. That is because the components are translated to macros before the page render.

You must pass them as the special argument `_attrs`.

```html+jinja
{#--- WRONG 😵 ---#}
<MyButton {{ attrs.render() }} />

{#--- GOOD 👍 ---#}
<MyButton _attrs={{ attrs }} />
<MyButton :_attrs="attrs" />
```
</Callout>

#### `.set(name=value, ...)`

Sets an attribute or property

- Pass a name and a value to set an attribute (e.g. `type="text"`)
- Use `True` as a value to set a property (e.g. `disabled`)
- Use `False` to remove an attribute or property
- If the attribute is "class", the new classes are appended to
  the old ones (if not repeated) instead of replacing them.
- The underscores in the names will be translated automatically to dashes,
  so `aria_selected` becomes the attribute `aria-selected`.

```html+jinja title="Adding attributes/properties"
{% do attrs.set(
  id="loremipsum",
  disabled=True,
  data_test="foobar",
  class="m-2 p-4",
) %}
```

```html+jinja title="Removing attributes/properties"
{% do attrs.set(
  title=False,
  disabled=False,
  data_test=False,
  class=False,
) %}
```

#### `.setdefault(name=value, ...)`

Adds an attribute, but only if it's not already present.

The underscores in the names will be translated automatically to dashes, so `aria_selected`
becomes the attribute `aria-selected`.

```html+jinja
{% do attrs.setdefault(
    aria_label="Products"
) %}
```

#### `.add_class(name1, name2, ...)`

Adds one or more classes to the list of classes, if not already present.

```html+jinja
{% do attrs.add_class("hidden") %}
{% do attrs.add_class("active", "animated") %}
```

#### `.remove_class(name1, name2, ...)`

Removes one or more classes from the list of classes.

```html+jinja
{% do attrs.remove_class("hidden") %}
{% do attrs.remove_class("active", "animated") %}
```

#### `.get(name, default=None)`

Returns the value of the attribute or property,
or the default value if it doesn't exist.

```html+jinja
{%- set role = attrs.get("role", "tab") %}
```

...