-
Notifications
You must be signed in to change notification settings - Fork 959
/
Copy pathphoenix_component.ex
3399 lines (2631 loc) · 105 KB
/
phoenix_component.ex
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule Phoenix.Component do
@moduledoc ~S'''
Define reusable function components with HEEx templates.
A function component is any function that receives an assigns
map as an argument and returns a rendered struct built with
[the `~H` sigil](`sigil_H/2`):
defmodule MyComponent do
# In Phoenix apps, the line is typically: use MyAppWeb, :html
use Phoenix.Component
def greet(assigns) do
~H"""
<p>Hello, {@name}!</p>
"""
end
end
This function uses the `~H` sigil to return a rendered template.
`~H` stands for HEEx (HTML + EEx). HEEx is a template language for
writing HTML mixed with Elixir interpolation. We can write Elixir
code inside `{...}` for HTML-aware interpolation inside tag attributes
and the body. We can also interpolate arbitrary HEEx blocks using `<%= ... %>`
We use `@name` to access the key `name` defined inside `assigns`.
When invoked within a `~H` sigil or HEEx template file:
```heex
<MyComponent.greet name="Jane" />
```
The following HTML is rendered:
```html
<p>Hello, Jane!</p>
```
If the function component is defined locally, or its module is imported,
then the caller can invoke the function directly without specifying the module:
```heex
<.greet name="Jane" />
```
For dynamic values, you can interpolate Elixir expressions into a function component:
```heex
<.greet name={@user.name} />
```
Function components can also accept blocks of HEEx content (more on this later):
```heex
<.card>
<p>This is the body of my card!</p>
</.card>
```
In this module we will learn how to build rich and composable components to
use in our applications.
## Attributes
`Phoenix.Component` provides the `attr/3` macro to declare what attributes the proceeding function
component expects to receive when invoked:
attr :name, :string, required: true
def greet(assigns) do
~H"""
<p>Hello, {@name}!</p>
"""
end
By calling `attr/3`, it is now clear that `greet/1` requires a string attribute called `name`
present in its assigns map to properly render. Failing to do so will result in a compilation
warning:
```heex
<MyComponent.greet />
<!-- warning: missing required attribute "name" for component MyAppWeb.MyComponent.greet/1
lib/app_web/my_component.ex:15 -->
```
Attributes can provide default values that are automatically merged into the assigns map:
attr :name, :string, default: "Bob"
Now you can invoke the function component without providing a value for `name`:
```heex
<.greet />
```
Rendering the following HTML:
```html
<p>Hello, Bob!</p>
```
Accessing an attribute which is required and does not have a default value will fail.
You must explicitly declare `default: nil` or assign a value programmatically with the
`assign_new/3` function.
Multiple attributes can be declared for the same function component:
attr :name, :string, required: true
attr :age, :integer, required: true
def celebrate(assigns) do
~H"""
<p>
Happy birthday {@name}!
You are {@age} years old.
</p>
"""
end
Allowing the caller to pass multiple values:
```heex
<.celebrate name={"Genevieve"} age={34} />
```
Rendering the following HTML:
```html
<p>
Happy birthday Genevieve!
You are 34 years old.
</p>
```
Multiple function components can be defined in the same module, with different attributes. In the
following example, `<Components.greet/>` requires a `name`, but *does not* require a `title`, and
`<Components.heading>` requires a `title`, but *does not* require a `name`.
defmodule Components do
# In Phoenix apps, the line is typically: use MyAppWeb, :html
use Phoenix.Component
attr :title, :string, required: true
def heading(assigns) do
~H"""
<h1>{@title}</h1>
"""
end
attr :name, :string, required: true
def greet(assigns) do
~H"""
<p>Hello {@name}</p>
"""
end
end
With the `attr/3` macro you have the core ingredients to create reusable function components.
But what if you need your function components to support dynamic attributes, such as common HTML
attributes to mix into a component's container?
## Global attributes
Global attributes are a set of attributes that a function component can accept when it
declares an attribute of type `:global`. By default, the set of attributes accepted are those
attributes common to all standard HTML tags.
See [Global attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes)
for a complete list of attributes.
Once a global attribute is declared, any number of attributes in the set can be passed by
the caller without having to modify the function component itself.
Below is an example of a function component that accepts a dynamic number of global attributes:
attr :message, :string, required: true
attr :rest, :global
def notification(assigns) do
~H"""
<span {@rest}>{@message}</span>
"""
end
The caller can pass multiple global attributes (such as `phx-*` bindings or the `class` attribute):
```heex
<.notification message="You've got mail!" class="bg-green-200" phx-click="close" />
```
Rendering the following HTML:
```html
<span class="bg-green-200" phx-click="close">You've got mail!</span>
```
Note that the function component did not have to explicitly declare a `class` or `phx-click`
attribute in order to render.
Global attributes can define defaults which are merged with attributes provided by the caller.
For example, you may declare a default `class` if the caller does not provide one:
attr :rest, :global, default: %{class: "bg-blue-200"}
Now you can call the function component without a `class` attribute:
```heex
<.notification message="You've got mail!" phx-click="close" />
```
Rendering the following HTML:
```html
<span class="bg-blue-200" phx-click="close">You've got mail!</span>
```
Note that the global attribute cannot be provided directly and doing so will emit
a warning. In other words, this is invalid:
```heex
<.notification message="You've got mail!" rest={%{"phx-click" => "close"}} />
```
### Included globals
You may also specify which attributes are included in addition to the known globals
with the `:include` option. For example to support the `form` attribute on a button
component:
```elixir
# <.button form="my-form"/>
attr :rest, :global, include: ~w(form)
slot :inner_block
def button(assigns) do
~H"""
<button {@rest}>{render_slot(@inner_block)}</button>
"""
end
```
The `:include` option is useful to apply global additions on a case-by-case basis,
but sometimes you want to extend existing components with new global attributes,
such as Alpine.js' `x-` prefixes, which we'll outline next.
### Custom global attribute prefixes
You can extend the set of global attributes by providing a list of attribute prefixes to
`use Phoenix.Component`. Like the default attributes common to all HTML elements,
any number of attributes that start with a global prefix will be accepted by function
components invoked by the current module. By default, the following prefixes are supported:
`phx-`, `aria-`, and `data-`. For example, to support the `x-` prefix used by
[Alpine.js](https://alpinejs.dev/), you can pass the `:global_prefixes` option to
`use Phoenix.Component`:
use Phoenix.Component, global_prefixes: ~w(x-)
In your Phoenix application, this is typically done in your
`lib/my_app_web.ex` file, inside the `def html` definition:
def html do
quote do
use Phoenix.Component, global_prefixes: ~w(x-)
# ...
end
end
Now all function components invoked by this module will accept any number of attributes
prefixed with `x-`, in addition to the default global prefixes.
You can learn more about attributes by reading the documentation for `attr/3`.
## Slots
In addition to attributes, function components can accept blocks of HEEx content, referred to
as slots. Slots enable further customization of the rendered HTML, as the caller can pass the
function component HEEx content they want the component to render. `Phoenix.Component` provides
the `slot/3` macro used to declare slots for function components:
slot :inner_block, required: true
def button(assigns) do
~H"""
<button>
{render_slot(@inner_block)}
</button>
"""
end
The expression `render_slot(@inner_block)` renders the HEEx content. You can invoke this function
component like so:
```heex
<.button>
This renders <strong>inside</strong> the button!
</.button>
```
Which renders the following HTML:
```html
<button>
This renders <strong>inside</strong> the button!
</button>
```
Like the `attr/3` macro, using the `slot/3` macro will provide compile-time validations.
For example, invoking `button/1` without a slot of HEEx content will result in a compilation
warning being emitted:
```heex
<.button />
<!-- warning: missing required slot "inner_block" for component MyAppWeb.MyComponent.button/1
lib/app_web/my_component.ex:15 -->
```
### The default slot
The example above uses the default slot, accessible as an assign named `@inner_block`, to render
HEEx content via the `render_slot/1` function.
If the values rendered in the slot need to be dynamic, you can pass a second value back to the
HEEx content by calling `render_slot/2`:
slot :inner_block, required: true
attr :entries, :list, default: []
def unordered_list(assigns) do
~H"""
<ul :for={entry <- @entries}>
<li>{render_slot(@inner_block, entry)}</li>
</ul>
"""
end
When invoking the function component, you can use the special attribute `:let` to take the value
that the function component passes back and bind it to a variable:
```heex
<.unordered_list :let={fruit} entries={~w(apples bananas cherries)}>
I like <b>{fruit}</b>!
</.unordered_list>
```
Rendering the following HTML:
```html
<ul>
<li>I like <b>apples</b>!</li>
<li>I like <b>bananas</b>!</li>
<li>I like <b>cherries</b>!</li>
</ul>
```
Now the separation of concerns is maintained: the caller can specify multiple values in a list
attribute without having to specify the HEEx content that surrounds and separates them.
### Named slots
In addition to the default slot, function components can accept multiple, named slots of HEEx
content. For example, imagine you want to create a modal that has a header, body, and footer:
slot :header
slot :inner_block, required: true
slot :footer, required: true
def modal(assigns) do
~H"""
<div class="modal">
<div class="modal-header">
{render_slot(@header) || "Modal"}
</div>
<div class="modal-body">
{render_slot(@inner_block)}
</div>
<div class="modal-footer">
{render_slot(@footer)}
</div>
</div>
"""
end
You can invoke this function component using the named slot HEEx syntax:
```heex
<.modal>
This is the body, everything not in a named slot is rendered in the default slot.
<:footer>
This is the bottom of the modal.
</:footer>
</.modal>
```
Rendering the following HTML:
```html
<div class="modal">
<div class="modal-header">
Modal.
</div>
<div class="modal-body">
This is the body, everything not in a named slot is rendered in the default slot.
</div>
<div class="modal-footer">
This is the bottom of the modal.
</div>
</div>
```
As shown in the example above, `render_slot/1` returns `nil` when an optional slot
is declared and none is given. This can be used to attach default behaviour.
### Slot attributes
Unlike the default slot, it is possible to pass a named slot multiple pieces of HEEx content.
Named slots can also accept attributes, defined by passing a block to the `slot/3` macro.
If multiple pieces of content are passed, `render_slot/2` will merge and render all the values.
Below is a table component illustrating multiple named slots with attributes:
slot :column, doc: "Columns with column labels" do
attr :label, :string, required: true, doc: "Column label"
end
attr :rows, :list, default: []
def table(assigns) do
~H"""
<table>
<tr>
<th :for={col <- @column}>{col.label}</th>
</tr>
<tr :for={row <- @rows}>
<td :for={col <- @column}>{render_slot(col, row)}</td>
</tr>
</table>
"""
end
You can invoke this function component like so:
```heex
<.table rows={[%{name: "Jane", age: "34"}, %{name: "Bob", age: "51"}]}>
<:column :let={user} label="Name">
{user.name}
</:column>
<:column :let={user} label="Age">
{user.age}
</:column>
</.table>
```
Rendering the following HTML:
```html
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jane</td>
<td>34</td>
</tr>
<tr>
<td>Bob</td>
<td>51</td>
</tr>
</table>
```
You can learn more about slots and the `slot/3` macro [in its documentation](`slot/3`).
## Embedding external template files
The `embed_templates/1` macro can be used to embed `.html.heex` files
as function components. The directory path is based on the current
module (`__DIR__`), and a wildcard pattern may be used to select all
files within a directory tree. For example, imagine a directory listing:
```plain
├── components.ex
├── cards
│ ├── pricing_card.html.heex
│ └── features_card.html.heex
```
Then you can embed the page templates in your `components.ex` module
and call them like any other function component:
defmodule MyAppWeb.Components do
use Phoenix.Component
embed_templates "cards/*"
def landing_hero(assigns) do
~H"""
<.pricing_card />
<.features_card />
"""
end
end
See `embed_templates/1` for more information, including declarative
assigns support for embedded templates.
## Debug Annotations
HEEx templates support debug annotations, which are special HTML comments
that wrap around rendered components to help you identify where markup
in your HTML document is rendered within your function component tree.
For example, imagine the following HEEx template:
```heex
<.header>
<.button>Click</.button>
</.header>
```
The HTML document would receive the following comments when debug annotations
are enabled:
```html
<!-- @caller lib/app_web/home_live.ex:20 -->
<!-- <AppWeb.CoreComponents.header> lib/app_web/core_components.ex:123 -->
<header class="p-5">
<!-- @caller lib/app_web/home_live.ex:48 -->
<!-- <AppWeb.CoreComponents.button> lib/app_web/core_components.ex:456 -->
<button class="px-2 bg-indigo-500 text-white">Click</button>
<!-- </AppWeb.CoreComponents.button> -->
</header>
<!-- </AppWeb.CoreComponents.header> -->
```
Debug annotations work across any `~H` or `.html.heex` template.
They can be enabled globally with the following configuration in your
`config/dev.exs` file:
config :phoenix_live_view, debug_heex_annotations: true
Changing this configuration will require `mix clean` and a full recompile.
## Dynamic Component Rendering
Sometimes you might need to decide at runtime which component to render.
Because function components are just regular functions, we can leverage
Elixir's `apply/3` function to dynamically call a module and/or function passed
in as an assign.
For example, using the following function component definition:
```elixir
attr :module, :atom, required: true
attr :function, :atom, required: true
# any shared attributes
attr :shared, :string, required: true
# any shared slots
slot :named_slot, required: true
slot :inner_block, required: true
def dynamic_component(assigns) do
{mod, assigns} = Map.pop(assigns, :module)
{func, assigns} = Map.pop(assigns, :function)
apply(mod, func, [assigns])
end
```
Then you can use the `dynamic_component` function like so:
```heex
<.dynamic_component
module={MyAppWeb.MyModule}
function={:my_function}
shared="Yay Elixir!"
>
<p>Howdy from the inner block!</p>
<:named_slot>
<p>Howdy from the named slot!</p>
</:named_slot>
</.dynamic_component>
```
This will call the `MyAppWeb.MyModule.my_function/1` function passing in the remaining assigns.
```elixir
defmodule MyAppWeb.MyModule do
attr :shared, :string, required: true
slot :named_slot, required: true
slot :inner_block, required: true
def my_function(assigns) do
~H"""
<p>Dynamic component with shared assigns: {@shared}</p>
{render_slot(@inner_block)}
{render_slot(@named_slot)}
"""
end
end
```
Resulting in the following HTML:
```html
<p>Dynamic component with shared assigns: Yay Elixir!</p>
<p>Howdy from the inner block!</p>
<p>Howdy from the named slot!</p>
```
Note that to get the most out of `Phoenix.Component`'s compile-time validations, it is beneficial to
define such a `dynamic_component` for a specific set of components sharing the same API, instead of
defining it for the general case.
In this example, we defined our `dynamic_component` to expect an assign called `shared`, as well as
two slots that all components we want to use with it must implement.
The called `my_function` component's attribute and slot definitions cannot be validated through the apply call.
'''
## Functions
alias Phoenix.LiveView.{Static, Socket, AsyncResult}
@reserved_assigns Phoenix.Component.Declarative.__reserved__()
# Note we allow live_action as it may be passed down to a component, so it is not listed
@non_assignables [:uploads, :streams, :socket, :myself]
@doc ~S'''
The `~H` sigil for writing HEEx templates inside source files.
`HEEx` is a HTML-aware and component-friendly extension of Elixir Embedded
language (`EEx`) that provides:
* Built-in handling of HTML attributes
* An HTML-like notation for injecting function components
* Compile-time validation of the structure of the template
* The ability to minimize the amount of data sent over the wire
* Out-of-the-box code formatting via `mix format`
## Example
~H"""
<div title="My div" class={@class}>
<p>Hello {@name}</p>
<MyApp.Weather.city name="Kraków"/>
</div>
"""
## Syntax
`HEEx` is built on top of Embedded Elixir (`EEx`). In this section, we are going to
cover the basic constructs in `HEEx` templates as well as its syntax extensions.
### Interpolation
`HEEx` allows using `{...}` for HTML-aware interpolation, inside tag attributes
as well as the body:
```heex
<p>Hello, {@name}</p>
```
If you want to interpolate an attribute, you write:
```heex
<div class={@class}>
...
</div>
```
You can put any Elixir expression between `{ ... }`. For example, if you want
to set classes, where some are static and others are dynamic, you can using
string interpolation:
```heex
<div class={"btn btn-#{@type}"}>
...
</div>
```
The following attribute values have special meaning on HTML tags:
* `true` - if a value is `true`, the attribute is rendered with no value at all.
For example, `<input required={true}>` is the same as `<input required>`;
* `false` or `nil` - if a value is `false` or `nil`, the attribute is omitted.
Note the `class` and `style` attributes will be rendered as empty strings,
instead of ommitted, which has the same effect as not rendering them, but
allows for rendering optimizations.
* `list` (only for the `class` attribute) - each element of the list is processed
as a different class. `nil` and `false` elements are discarded.
For multiple dynamic attributes, you can use the same notation but without
assigning the expression to any specific attribute:
```heex
<div {@dynamic_attrs}>
...
</div>
```
In this case, the expression inside `{...}` must be either a keyword list or
a map containing the key-value pairs representing the dynamic attributes.
If using a map, ensure your keys are atoms.
### Interpolating blocks
The curly braces syntax is the default mechanism for interpolating code.
However, it cannot be used in all scenarios, in particular:
* Curly braces cannot be used inside `<script>` and `<style>` tags,
as that would make writing JS and CSS quite tedious. You can also
fully disable curly braces interpolation in a given tag and
its children by adding the `phx-no-curly-interpolation` attribute
* it does not support multiline block constructs, such as `if`,
`case`, and similar
For example, if you need to interpolate a string inside a script tag,
you could do:
```heex
<script>
window.URL = "<%= @my_url %>"
</script>
```
Similarly, for block constructs in Elixir, you can write:
```heex
<%= if @show_greeting? do %>
<p>Hello, {@name}</p>
<% end %>
```
However, for conditionals and for-comprehensions, there are built-in constructs
in HEEx too, which we will explore next.
> #### Curly braces in text within tag bodies {: .tip}
>
> If you have text in your tag bodies, which includes curly braces you can use
> `{` or `<%= "{" %>` to prevent them from being considered the start of
> interpolation.
### Special attributes
Apart from normal HTML attributes, HEEx also supports some special attributes
such as `:let` and `:for`.
#### :let
This is used by components and slots that want to yield a value back to the
caller. For an example, see how `form/1` works:
```heex
<.form :let={f} for={@form} phx-change="validate" phx-submit="save">
<.input field={f[:username]} type="text" />
...
</.form>
```
Notice how the variable `f`, defined by `.form` is used by your `input` component.
The `Phoenix.Component` module has detailed documentation on how to use and
implement such functionality.
#### :if and :for
It is a syntax sugar for `<%= if .. do %>` and `<%= for .. do %>` that can be
used in regular HTML, function components, and slots.
For example in an HTML tag:
```heex
<table id="admin-table" :if={@admin?}>
<tr :for={user <- @users}>
<td>{user.name}</td>
</tr>
<table>
```
The snippet above will only render the table if `@admin?` is true,
and generate a `tr` per user as you would expect from the collection.
`:for` can be used similarly in function components:
```heex
<.error :for={msg <- @errors} message={msg}/>
```
Which is equivalent to writing:
```heex
<%= for msg <- @errors do %>
<.error message={msg} />
<% end %>
```
And `:for` in slots behaves the same way:
```heex
<.table id="my-table" rows={@users}>
<:col :for={header <- @headers} :let={user}>
<td>{user[header]}</td>
</:col>
<table>
```
You can also combine `:for` and `:if` for tags, components, and slot to act as a filter:
```heex
<.error :for={msg <- @errors} :if={msg != nil} message={msg} />
```
Note that unlike Elixir's regular `for`, HEEx' `:for` does not support multiple
generators in one expression. In such cases, you must use `EEx`'s blocks.
### Function components
Function components are stateless components implemented as pure functions
with the help of the `Phoenix.Component` module. They can be either local
(same module) or remote (external module).
`HEEx` allows invoking these function components directly in the template
using an HTML-like notation. For example, a remote function:
```heex
<MyApp.Weather.city name="Kraków"/>
```
A local function can be invoked with a leading dot:
```heex
<.city name="Kraków"/>
```
where the component could be defined as follows:
defmodule MyApp.Weather do
use Phoenix.Component
def city(assigns) do
~H"""
The chosen city is: {@name}.
"""
end
def country(assigns) do
~H"""
The chosen country is: {@name}.
"""
end
end
It is typically best to group related functions into a single module, as
opposed to having many modules with a single `render/1` function. Function
components support other important features, such as slots. You can learn
more about components in `Phoenix.Component`.
## Code formatting
You can automatically format HEEx templates (.heex) and `~H` sigils
using `Phoenix.LiveView.HTMLFormatter`. Please check that module
for more information.
'''
@doc type: :macro
defmacro sigil_H({:<<>>, meta, [expr]}, modifiers)
when modifiers == [] or modifiers == ~c"noformat" do
if not Macro.Env.has_var?(__CALLER__, {:assigns, nil}) do
raise "~H requires a variable named \"assigns\" to exist and be set to a map"
end
options = [
engine: Phoenix.LiveView.TagEngine,
file: __CALLER__.file,
line: __CALLER__.line + 1,
caller: __CALLER__,
indentation: meta[:indentation] || 0,
source: expr,
tag_handler: Phoenix.LiveView.HTMLEngine
]
EEx.compile_string(expr, options)
end
@doc ~S'''
Filters the assigns as a list of keywords for use in dynamic tag attributes.
One should prefer to use declarative assigns and `:global` attributes
over this function.
## Examples
Imagine the following `my_link` component which allows a caller
to pass a `new_window` assign, along with any other attributes they
would like to add to the element, such as class, data attributes, etc:
```heex
<.my_link to="/" id={@id} new_window={true} class="my-class">Home</.my_link>
```
We could support the dynamic attributes with the following component:
def my_link(assigns) do
target = if assigns[:new_window], do: "_blank", else: false
extra = assigns_to_attributes(assigns, [:new_window, :to])
assigns =
assigns
|> assign(:target, target)
|> assign(:extra, extra)
~H"""
<a href={@to} target={@target} {@extra}>
{render_slot(@inner_block)}
</a>
"""
end
The above would result in the following rendered HTML:
```heex
<a href="/" target="_blank" id="1" class="my-class">Home</a>
```
The second argument (optional) to `assigns_to_attributes` is a list of keys to
exclude. It typically includes reserved keys by the component itself, which either
do not belong in the markup, or are already handled explicitly by the component.
'''
def assigns_to_attributes(assigns, exclude \\ []) do
excluded_keys = @reserved_assigns ++ exclude
for {key, val} <- assigns, key not in excluded_keys, into: [], do: {key, val}
end
@doc """
Renders a LiveView within a template.
This is useful in two situations:
* When rendering a child LiveView inside a LiveView.
* When rendering a LiveView inside a regular (non-live) controller/view.
## Options
* `:session` - a map of binary keys with extra session data to be serialized and sent
to the client. All session data currently in the connection is automatically available
in LiveViews. You can use this option to provide extra data. Remember all session data is
serialized and sent to the client, so you should always keep the data in the session
to a minimum. For example, instead of storing a User struct, you should store the "user_id"
and load the User when the LiveView mounts.
* `:container` - an optional tuple for the HTML tag and DOM attributes to be used for the
LiveView container. For example: `{:li, style: "color: blue;"}`. By default it uses the module
definition container. See the "Containers" section below for more information.
* `:id` - both the DOM ID and the ID to uniquely identify a LiveView. An `:id` is
automatically generated when rendering root LiveViews but it is a required option when
rendering a child LiveView.
* `:sticky` - an optional flag to maintain the LiveView across live redirects, even if it is
nested within another LiveView. Note that this only works for LiveViews that are in the same
[live_session](`Phoenix.LiveView.Router.live_session/3`).
If you are rendering the sticky view within make sure that the sticky view itself does not use
the same layout. You can do so by returning `{:ok, socket, layout: false}` from mount.
## Examples
When rendering from a controller/view, you can call:
```heex
{live_render(@conn, MyApp.ThermostatLive)}
```
Or:
```heex
{live_render(@conn, MyApp.ThermostatLive, session: %{"home_id" => @home.id})}
```
Within another LiveView, you must pass the `:id` option:
```heex
{live_render(@socket, MyApp.ThermostatLive, id: "thermostat")}
```
## Containers
When a LiveView is rendered, its contents are wrapped in a container. By default,
the container is a `div` tag with a handful of LiveView-specific attributes.
The container can be customized in different ways:
* You can change the default `container` on `use Phoenix.LiveView`: