Repository navigation
Expand file tree
/
Copy pathllms-full.txt
More file actions
4469 lines (2991 loc) · 185 KB
/
Copy pathllms-full.txt
File metadata and controls
4469 lines (2991 loc) · 185 KB
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
# Hologram
> Full-stack isomorphic Elixir web framework that lets you build interactive web applications entirely in Elixir, without writing JavaScript.
- [Website](https://hologram.page)
- [GitHub](https://github.com/bartblast/hologram)
- [HexDocs](https://hexdocs.pm/hologram)
## Guides
### Introduction
Hologram is a full-stack isomorphic Elixir web framework that runs on top of Phoenix. It lets developers create dynamic, interactive web applications entirely in Elixir. Through intelligent code analysis and transformation, Hologram compiles the necessary parts of your Elixir code to JavaScript, delivering modern frontend functionality without requiring any JavaScript frameworks or direct JavaScript coding.
#### Key Features
- Pure Elixir development: write your entire web application in Elixir without needing to write JavaScript code
- Client-side state: state management happens in the browser for snappy user interfaces
- Automatic code distribution: Hologram automatically handles the separation and conversion of client/server code
- Seamless communication: client-server interaction happens automatically through HTTP/2 persistent connections - no manual setup needed, with the speed of WebSockets and better scalability
#### Framework Philosophy
Hologram was created with several key principles in mind:
- Developer experience: focus on writing features instead of boilerplate code
- Convention over configuration: follow established patterns while maintaining flexibility
- Unified language: use Elixir for both client and server-side logic
- Component-based architecture: build applications using reusable building blocks
#### Inspiration
Hologram draws inspiration from several successful web technologies: Elm, Phoenix LiveView, Surface and Ruby on Rails.
### Installation
This guide will walk you through the installation process step by step.
#### Prerequisites
- `Elixir` version 1.19 or higher
- `OTP` version 28.1 or higher
- A working `Phoenix` application (see Phoenix installation guide: https://hexdocs.pm/phoenix/installation.html#phoenix)
- `Node.js` version 20 or higher and `npm`, if not already installed, you can get them via `asdf`:
```
$ asdf plugin add nodejs
$ asdf install nodejs latest
$ asdf global nodejs latest
```
See asdf installation guide (https://asdf-vm.com/guide/getting-started.html) if you need to install asdf first.
#### 1. Add Hologram Package
Add the Hologram package to your dependencies list in `mix.exs`:
```elixir
{:hologram, "~> 0.8"},
```
#### 2. Fetch Dependencies
Run the following command to fetch the Hologram package:
```
$ mix deps.get
```
#### 3. Configure Compiler
Add the Hologram compiler to your project configuration in `mix.exs`:
```elixir
def project do
[
# ...
compilers: Mix.compilers() ++ [:hologram],
# ...
]
end
```
#### 4. Configure Router
Add the Hologram router plug before your Phoenix router plug in your endpoint:
```elixir
defmodule MyAppWeb.Endpoint do
# ...
plug Hologram.Router
plug MyAppWeb.Router
end
```
#### 5. Configure Static Asset Serving
Add the Hologram directory to the list of served static directories in your endpoint:
```elixir
plug Plug.Static,
# ...
only: ["hologram" | MyAppWeb.static_paths()]
```
#### 6. Configure Formatter
Import Hologram formatter rules in `.formatter.exs`:
```elixir
[
# ...
import_deps: [..., :hologram]
# ...
]
```
#### 7. Update GitIgnore
Add the following line to your `.gitignore` file to exclude Hologram generated JavaScript bundles:
```
# Hologram generated JavaScript bundles.
/priv/static/hologram/
```
#### 8. Optional: Configure App Directory
Many developers prefer to organize their Hologram pages and components in an `app` directory outside of `lib` for better project structure. If you want to use this approach, modify your existing `elixirc_paths/1` functions in `mix.exs` to include the `app` directory:
```elixir
defp elixirc_paths(:test), do: ["app", "lib", "test/support"]
defp elixirc_paths(_env), do: ["app", "lib"]
```
This allows you to organize your code like `app/pages/`, `app/components/`, etc., which many developers find cleaner than keeping everything in `lib/`.
#### Umbrella Projects
Hologram supports umbrella projects. The steps above apply to the child app that owns the Phoenix endpoint - it takes the Hologram dependency (step 1), the compiler entry (step 3), the router plug (step 4), the static asset configuration (step 5) and the gitignore entry (step 7).
Child apps that only define pages and components take the dependency alone, without the compiler entry. Their pages are discovered and bundled when the endpoint app compiles.
A few umbrella-specific details:
- Endpoint configuration lives in the umbrella root `config` directory, as it does for any umbrella app.
- Run `mix holo` from the umbrella root. Started from inside the endpoint app it watches only that app's sources, so changes in sibling apps will not trigger a live reload.
- Add `listeners: [Phoenix.CodeReloader]` to the `project` config in the umbrella root `mix.exs`. Mix reads listeners from the project it runs as, so the entry Phoenix generates in the endpoint app is not seen when `mix holo` runs from the root, and every reload logs a missing-listener warning.
- npm packages go in an `assets` directory at the umbrella root, and are resolved from there for every child app.
- Hologram supports one endpoint app per running BEAM instance. If several apps in the umbrella have a configured Phoenix endpoint, Hologram raises a descriptive error.
#### Next Steps
After completing the installation, you can start building your isomorphic web application with Hologram. For more information on how to use Hologram's features, please refer to the website's Documentation section.
#### Notes
- Make sure all dependencies are properly installed and configured
- Verify that your Phoenix application is properly set up before installing Hologram
### Quick Start
Before starting, make sure you have installed Hologram correctly by following the Installation Guide.
Let's build a simple blog application to demonstrate Hologram's key features. Our blog will have:
- A home page listing blog posts
- Individual post pages
- A layout with navigation
- The ability to like posts
#### Creating the Layout
First, let's create a layout that will be shared across all pages:
```elixir
defmodule Blog.MainLayout do
use Hologram.Component
alias Hologram.UI.Link
alias Hologram.UI.Runtime
def template do
~HOLO"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My Blog</title>
<Runtime />
</head>
<body>
<nav>
<Link to={Blog.HomePage}>Home</Link>
</nav>
<main>
<slot />
</main>
</body>
</html>
"""
end
end
```
#### Creating the Home Page
Now let's create the home page that lists blog posts:
```elixir
defmodule Blog.HomePage do
use Hologram.Page
alias Blog.Components.PostPreview
route "/"
layout Blog.MainLayout
def init(_params, component, _server) do
# In real app, fetch from database
posts = [
%{id: 1, title: "First Post", excerpt: "This is my first post"},
%{id: 2, title: "Second Post", excerpt: nil}
]
put_state(component, :posts, posts)
end
def template do
~HOLO"""
<h1>Welcome to my Blog</h1>
<div class="posts">
{%for post <- @posts}
<PostPreview post={post} />
{/for}
</div>
"""
end
end
```
#### Creating a Post Preview Component
Let's create a reusable component for displaying post previews:
```elixir
defmodule Blog.Components.PostPreview do
use Hologram.Component
alias Hologram.UI.Link
prop :post, :map
def template do
~HOLO"""
<article class="post-preview">
<h2>{@post.title}</h2>
<p>{@post.excerpt}</p>
<Link to={Blog.PostPage, id: @post.id}>Read more</Link>
</article>
"""
end
end
```
#### Creating the Post Page
Now let's create a page for individual posts with a like button:
```elixir
defmodule Blog.PostPage do
use Hologram.Page
route "/posts/:id"
param :id, :integer
layout Blog.MainLayout
def init(params, component, _server) do
# In real app, fetch from database
post = %{
id: params.id,
title: "Example Post",
content: "This is the full content...",
likes: 0
}
put_state(component, :post, post)
end
def template do
~HOLO"""
<article>
<h1>{@post.title}</h1>
<p>{@post.content}</p>
<div class="likes">
Likes: {@post.likes}
<button $click="like_post">Like</button>
</div>
</article>
"""
end
def action(:like_post, _params, component) do
# Update likes locally first for instant feedback
component
|> put_state([:post, :likes], component.state.post.likes + 1)
|> put_command(:save_like, post_id: component.state.post.id)
end
def command(:save_like, params, server) do
# In real app, save to database
IO.puts("Liked post #{params.post_id}")
server
end
end
```
#### Key Concepts Demonstrated
1. Pages: both `HomePage` and `PostPage` are Hologram pages with their own routes
2. Components: the `PostPreview` component shows how to create reusable UI elements
3. Layout: the `MainLayout` provides a consistent structure across pages
4. Template Syntax:
- Using `{%for}` loops
- Interpolating values with `{@var}`
- Event binding with `$click`
5. Navigation: using `Link` component to navigate between pages
6. State Management: using `put_state/3` to manage component state
7. Actions & Commands: the like button demonstrates:
- Client-side action for immediate UI update
- Server-side command for persistence
8. Props: component properties with the `prop/2` macro
9. Parameters: route parameters with the `param/2` macro
This example demonstrates the basic building blocks of a Hologram application. The framework handles the client-server communication and state management automatically, letting you focus on building features.
Remember that Hologram keeps state on the client side for better performance while using commands for server-side operations when needed.
## Documentation
### Architecture
Hologram's architecture is designed around simplicity and developer experience. Here's how it works:
#### Pages and Components
The framework breaks down web applications into two fundamental building blocks:
- Pages: top-level components that represent different routes in your application
- Components: reusable UI elements that can be composed together
#### Code Distribution
Hologram automatically analyzes your code and:
1. Determines which parts should run on the client vs server
2. Compiles necessary Elixir code to JavaScript for browser execution
3. Ships only the code and protocol implementations your app can actually reach, keeping client bundles small
4. Sets up all required client-server communication
Protocol implementations are included by type reachability. A struct's implementations (e.g. `String.Chars`) ship to the browser when the compiler finds the struct type in client-reachable code, in server-executed `init` or command code, or in action broadcasting code - not merely because a dependency defines them. If a type is resolved dynamically at runtime (for example from a string or external data), reference its struct module anywhere in client-reachable code to include its implementations.
#### Client-Side State
State is maintained in the browser, which:
- Enables immediate UI updates
- Reduces server load
- Simplifies the programming model
#### Actions and Commands
Code execution is organized into two types of operations:
- Actions: client-side operations that run in the browser
- Commands: server-side operations for tasks like database access
Both can be triggered by user interactions, and they can trigger each other.
#### HTTP/2 Communication
Client-server communication happens automatically through HTTP/2 persistent connections:
- No manual HTTP configuration needed
- No boilerplate code required
- Handles all action-command interactions
- Practically as fast as WebSockets for real-time updates
- Lower server resource consumption - no continuous connection overhead per user
- Easier debugging with standard HTTP tools and browser DevTools
- Works seamlessly through corporate proxies and firewalls
#### Runtime Behavior
The framework:
1. Loads the initial page from the server
2. Mounts the page in the browser
3. Manages the virtual DOM for efficient updates
4. Handles all client-server communication automatically
### Template Syntax
Hologram templates use a custom syntax called "HOLO" that combines HTML with Elixir expressions.
#### Regular HTML Markup
You can use standard HTML elements and attributes in your templates:
```holo
<div class="container">
<h1>Hello World</h1>
<p>This is a paragraph.</p>
</div>
```
#### Accessing Props and State
Props and state are accessible in templates using the `@var` syntax. This provides a convenient way to reference component data. For example, if you have a prop or state variable named `count`, you can access it as `@count` in your template.
In the following sections, you'll see how to use these variables in Elixir expressions for interpolation and control flow blocks.
#### Component Nodes
Components can be used as custom elements in your templates. They can receive props (properties) as attributes. String props can be given as regular double-quoted attributes, while other Elixir values (like numbers, booleans, or expressions) are given using curly braces syntax:
```holo
<MyComponent title="Hello" count={42} />
```
For more information about components and their props, see the Components documentation.
#### Dynamic Nodes
Which node a tag renders doesn't have to be decided literally. A braced Elixir expression in tag-name position is evaluated at render time and its value decides what gets rendered: a component module renders that component, a string renders an HTML element with that tag name, and any other value raises an `ArgumentError`.
Components are the usual reason to reach for this - a widget chosen by a content type, a step in a wizard, a row in a heterogeneous list. The attributes become the component's props and the content between the tags becomes its default slot, exactly as with a statically named component:
```holo
<{@module} cid="my_component" title="Hello" />
<{@module} cid="my_component">slot content</{@module}>
```
A page module isn't valid here, even though a page is a kind of component itself - it's a root one, owning a route, taking its params from the URL and picking a layout, so it only makes sense at the root of a render, never as a node inside another template.
A call site that can't name the module statically usually can't name the props either, so dynamic tags pair naturally with the attribute and prop spread described below - both the module and its props come from the data:
```holo
{%for widget <- @widgets}
<{widget.module} ...{widget.props} />
{/for}
```
A string value renders an element instead, with the attributes becoming DOM attributes and event bindings - so a heading level or an anchor-versus-button choice can be kept in state. Whatever string arrives is the tag that gets rendered, so tag names must never come from untrusted input:
```holo
<{@heading_tag} class="heading">{@text}</{@heading_tag}>
```
The expression is ordinary Elixir compiled in the template's module context, so aliases in scope apply and `@var` resolves to a prop or state value, exactly as anywhere else in a template. Most often it's simply a state value holding a module or a tag name:
```elixir
put_state(component, module: MyButton, heading_tag: "h2")
```
Nothing beyond the dispatch is new. Once resolved, a dynamic node behaves exactly like the equivalent static one - `<{MyButton} label="x">` is `<MyButton label="x">` and `<{"div"} class="x">` is `<div class="x">`. All prop, attribute, event, void element, spread and slot semantics carry over unchanged.
Since dispatch happens per render, changing the module under a given `cid` replaces the component: the outgoing one is unmounted and the incoming one initializes its own state from scratch.
##### Closing Tags
A dynamic tag with children is closed with `</{expr}>`, repeating the opening expression verbatim, as in the examples above.
That repetition is a good reason to keep the expression short. Logic written inline - an `if` picking between an anchor and a button, a `case` mapping a content type to a component - gets spelled out twice, once in each tag, and the two copies can drift apart. Keep the value in state or a prop, or compute it with a helper function.
##### Module Reachability
To render a dynamic component on the client, the compiler must know its module at build time. It bundles a component whenever the module atom appears as a literal in code it can see - a template, any client-reachable function, a page's or component's `init/3` or `command/3` server callback, or any code that broadcasts an action - `put_broadcast/3,4` inside a handler, `Hologram.Realtime.broadcast_action/2,3` outside one. So a module put into state by `init/3` or sent back in action params by `command/3` works without any extra declaration.
The search follows calls forward, so functions those callbacks call count too, but their own callers don't - a module picked elsewhere and passed down into a broadcasting helper won't be found. Modules that exist only at runtime don't work at all: ones built with `Module.concat/1`, resolved with `String.to_existing_atom/1`, or read from the database or config without a literal anywhere in the app's code are not bundled, and rendering them on the client raises.
A component referenced in broadcast code goes into the shared runtime bundle rather than a page bundle, so it ships with every page - a broadcast is addressed to a `cid`, and which page has that `cid` mounted is only known at runtime.
#### Elixir Expression Interpolation
You can embed Elixir expressions in your templates using curly braces:
##### Inside Text
```holo
<p>Hello, {@name}!</p>
```
##### Inside Attributes and Props
You can interpolate Elixir expressions in attributes and props in two ways.
First, you can interpolate the entire attribute value:
```holo
<div class={@class_name}>Content</div>
```
Or you can interpolate part of the attribute value within double quotes:
```holo
<div class="base-class {@dynamic_class}">Content</div>
```
Both approaches work for regular HTML attributes and component props:
```holo
<MyComponent count={Enum.count(@items)} label="Welcome, {@count}" />
```
###### Conditional Attributes
When an attribute expression evaluates to a falsy value (`nil` or `false`), the attribute is not rendered at all. This is useful for conditional attributes:
```holo
<button disabled={@loading?}>Submit</button>
<div class={if @active? do "active" else nil end}>Content</div>
```
In this example, when `@loading?` is `false`, the `disabled` attribute won't appear in the HTML. Similarly, when `@active?` is `false`, the `class` attribute will be omitted entirely.
##### Security: Automatic HTML Escaping
For security purposes, interpolated expressions in text content and HTML attributes are automatically HTML-escaped to prevent XSS (Cross-Site Scripting) attacks. This means that potentially dangerous characters like `<`, `>`, `&`, and quotes are converted to their HTML entity equivalents (`<`, `>`, `&`, etc.).
```holo
<p>User input: {@user_input}</p>
```
If `@user_input` contains `"<script>alert('XSS')</script>"`, it will be safely rendered as escaped text rather than executed as JavaScript. This escaping happens automatically for all values interpolated in text content and HTML attributes.
###### Inside Script Elements
A `<script>` element is different, because the browser hands its text straight to the JavaScript engine without turning HTML entities back into characters. An interpolated expression there is escaped as the text of a JavaScript string literal instead. Write it between quotes - double, single or backtick, whichever the surrounding code uses - and the script receives the value exactly as it is:
```holo
<script>
gtag("config", "{@tracking_id}");
</script>
```
Whatever the value holds, it cannot end the string literal it sits in, and it cannot end the script element - so the `"</script>"` case above is covered here too.
An interpolation written without quotes, such as `var x = {@value};`, puts the value in code position rather than text position. It is escaped like any other interpolation in a script, but the escaping only means something inside a string literal. Outside one, a value of `alert(1)` has nothing to escape and simply runs, while a value holding a quote or a `<` becomes `\"` or `\u{3C}`, which are a syntax error in code position and stop the whole script.
Being valid JavaScript is not the same as being safe. Write a bare interpolation only for code your own application generates, such as a number or a boolean, and never for anything coming from a user, a request or a database. To pass structured data, interpolate into a string and parse it: `JSON.parse("{@json}")`.
#### Attribute and Prop Spread
A bare braced expression prefixed with `...` injects a map's or keyword list's entries as the tag's attributes (on elements) or props (on components). The `...` marker sits outside the braces, so their content is ordinary Elixir - any expression is allowed:
```holo
<div class="btn" ...{@html_attrs}>Content</div>
<MyComponent title="Hello" ...{@props} />
```
The expression must evaluate to a map or a keyword list - anything else, including `nil`, raises an `ArgumentError`. Bare keyword shorthand works inside the braces, the same convention event bindings already use:
```holo
<div ...{class: "btn", data: [user_id: @id]}>Content</div>
```
Spread adds no rules of its own: every entry behaves exactly as if you had written it as a named attribute or prop at that position. On elements, values are stringified and falsy ones drop the attribute, exactly as described above. On components, values stay raw Elixir terms and undeclared keys are silently ignored, just like named props.
##### Attribute Names
On elements, underscores in a key convert to hyphens, whether the key is an atom or a string - `:data_value` and `"data_value"` both render `data-value`. A map or keyword list value nests, composing the name with hyphens at each level, so the example above renders `data-user-id`. Literal markup is never touched, so writing the attribute out by hand remains the exact-name escape hatch.
On components, neither rule applies. A key like `:my_prop` sets the prop declared with exactly that name, with no hyphen conversion, since prop names are Elixir atoms. Values don't nest either - a map value is not expanded into multiple props, it's simply what that one prop receives. The `cid` prop may be supplied through a spread.
Event bindings cannot be set through a spread. A `$`-prefixed key raises an `ArgumentError`, because silently not binding an intended event would be worse than erroring. Write events as literal attributes. They don't need a spread to be conditional anyway - a binding whose operation resolves to `nil` is switched off, as described in the Events documentation.
The entries a single spread expands to render in alphabetical order. Map key order is undefined in Elixir, so sorting is what keeps the output reproducible. Attributes you write out yourself keep their position.
##### Precedence
Multiple spreads are allowed, and they interleave freely with named attributes and props. Names resolve by position, and the last one wins - so a literal before a spread is a default, and a literal after it is forced:
```holo
<div title="default" ...{@attrs}>Content</div>
<div ...{@attrs} title="forced">Content</div>
<div ...{@base} ...{@overrides}>Content</div>
```
##### Forwarding Wrapper
There is nothing to declare on the receiving component - spread resolves at the call site, so props arrive indistinguishable from named ones and every existing component is already a valid target. To let a wrapper pass arbitrary attributes through to an inner element, declare an ordinary map prop:
```elixir
prop :html_attrs, :map
```
and spread it in the wrapper's template:
```holo
<button class="fancy" ...{@html_attrs}><slot /></button>
```
Callers then pass the attributes as a single prop:
```holo
<FancyButton html_attrs={@button_attrs}>Save</FancyButton>
```
#### Control Flow Blocks
##### If Block
Use `{%if}` blocks for conditional rendering. The condition follows Elixir's truthiness rules - only `nil` and `false` are considered falsy, while any other value is considered truthy. You can optionally include an `{%else}` branch.
Simple if block without else:
```holo
<div>
{%if @show_message?}
<p>Message is visible</p>
{/if}
</div>
```
If block with else branch:
```holo
<div>
{%if @show_message?}
<p>Message is visible</p>
{%else}
<p>Message is hidden</p>
{/if}
</div>
```
##### For Block
Use `{%for}` blocks to iterate over collections. The syntax follows Elixir's comprehension rules, allowing you to use the same pattern matching and filtering capabilities as regular Elixir comprehensions.
```holo
<ul>
{%for item <- @items}
<li>{item.name}</li>
{/for}
</ul>
```
#### Event Binding
You can bind events to elements using event attributes. For detailed information about event binding syntax and available event types, see the Events documentation.
#### Escaping Curly Braces
To output literal curly braces in your template, escape them with a backslash:
```holo
<p>\{@literal\} {@variable}</p>
```
#### Raw Block
Use `{%raw}` blocks to output content without processing:
```holo
<div>
{%raw}
This content will be output as-is, including any \{curly braces\} or \{%control\}...\{/flow\} syntax.
{/raw}
</div>
```
#### HTML Comments
You can use standard HTML comments in your templates:
```holo
<div>
<!-- This is a comment that will be visible in the HTML output -->
<p>Content</p>
</div>
```
### Components
Components are the building blocks of Hologram applications. They are reusable pieces of UI that can be composed together to create complex interfaces.
#### Basic Example
Here's a simple stateless component that displays a greeting:
```elixir
defmodule Greeting do
use Hologram.Component
prop :name, :string
prop :title, :string, default: "Mr."
def template do
~HOLO"""
<p>Hello, {@title} {@name}!</p>
"""
end
end
```
Usage:
```holo
<Greeting name="Wick" title="Mr." />
```
#### Props
Props are the primary way to pass data to components.
They are defined using the `prop/2` macro receiving `name` and `type` params:
```elixir
prop :user_id, :integer
```
or `prop/3` macro that can receive the third `opts` param:
```elixir
prop :user_id, :integer, default: 123
```
##### Types
Props can be typed using the following types:
- `:any` - Any type (no type checking)
- `:atom` - Atoms
- `:boolean` - Booleans
- `:bitstring` - Bitstrings
- `:float` - Floats
- `:function` - Functions
- `:integer` - Integers
- `:list` - Lists
- `:map` - Maps
- `:pid` - PIDs
- `:port` - Ports
- `:reference` - References
- `:string` - Strings (UTF-8 encoded binaries)
- `:tuple` - Tuples
##### Options
Props can be configured using the `default`, `from_context`, `required` and `values` options. Any other option is a compile error, so a typo such as `defualt:` fails the build instead of being silently ignored.
###### Default Value
Set a default value for optional props using the `default` option:
```elixir
prop :count, :integer, default: 0
```
###### Context Source
Props can be sourced from the Context using the `from_context` option. This is useful for accessing shared data across components:
```elixir
prop :user, :map, from_context: :current_user
```
For more information about Context, see the Context page.
###### Required
Mark a prop as mandatory using the `required` option:
```elixir
prop :size, :atom, required: true
```
It can't be combined with `default`, since a prop with a default is never missing. It can be combined with `from_context`, which then means the Context must supply the value.
###### Allowed Values
Restrict a prop to a set of acceptable values using the `values` option:
```elixir
prop :size, :atom, values: [:small, :large]
```
A `default` value that isn't in the prop's own `values` list is a compile error.
###### When Violations Are Reported
A missing required prop is reported at compile time wherever a template writes the component out, and so is any value the compiler can work out without running anything: plain text with nothing interpolated into it, or a literal - `:small`, `"small"`, `1`, `true`, and composites built from them such as `{[:small, :large]}` or `{%{size: :small}}`. The build fails, naming the component and the template it was used in.
Everything else is checked while rendering, and raises `Hologram.PropError` naming the template the component was rendered from. That covers a prop arriving through a spread, a component chosen by a dynamic tag, a prop sourced from the Context, an interpolated value such as `size="a{@b}"`, and any expression - including one nested inside an otherwise literal value, such as `{[:small, @other]}`.
#### Stateful vs. Stateless Components
Components can be either stateful or stateless:
- **Stateless Components**: Don't maintain any internal state. They render based solely on their props.
- **Stateful Components**: Maintain internal state and can update it over time. They are identified by a unique `cid` (component ID) and can have actions and commands. Stateful components can be initialized using either `init/3` (server-side) or `init/2` (client-side) functions.
##### Component ID (cid)
To make a component stateful, provide a `cid` when using it:
```holo
<Assassin cid="baba_yaga" name="John Wick" kill_count={439} />
```
The `cid` is used to target actions and commands at specific components using the `target` field:
```holo
<button $click={action: :increment_kills, target: "baba_yaga"}>Add Another One</button>
```
##### Initialization
**Important:** Each stateful component instance is initialized **exactly once** during its lifetime. The initialization method depends on where the component's lifecycle starts:
- `init/3`: When the component's lifecycle starts as part of server-side page rendering (pages are always first rendered on the server when you navigate to them)
- `init/2`: When the component's lifecycle starts by being dynamically added to an already-loaded page
A component module can define both functions since you may have multiple instances - some starting on the server and others starting directly on the client. Each instance has its own unique `cid` and separate state.
###### Server-side Initialization (init/3)
Called when the component starts its lifecycle on the server. Provides access to cookies and session data through the `Server` struct. It receives three parameters:
- `props` - a map containing the component's props
- `component` - a `Component` struct representing the client-side state container
- `server` - a `Server` struct representing the server-side state container (with access to cookies and session)
The function should return either:
- A tuple containing `Component` and `Server` structs when modifying both client and server state
- Just a `Component` struct when only modifying client state
- Just a `Server` struct when only modifying server state
Example:
```elixir
def init(_props, component, server) do
component = put_state(component, :kill_count, 439)
server = put_session(server, :name, "John Wick")
{component, server}
end
```
###### Client-side Initialization (init/2)
Called when the component starts its lifecycle directly on the client. No access to cookies or session data since they are managed through the `Server` struct. It receives two parameters:
- `props` - a map containing the component's props
- `component` - a `Component` struct representing the client-side state container
The function should return a `Component` struct with any initial state.
Example:
```elixir
def init(_props, component) do
put_state(component, kill_count: 439, name: "John Wick")
end
```
###### Chaining Actions in Initialization
In both `init/3` and `init/2` functions, you can chain actions that will be executed when the component is mounted on the client. This is useful for triggering setup logic, animations, or data loading after the component becomes available in the browser.
Server-side initialization (`init/3`):
```elixir
def init(_props, component, _server) do
put_action(component, :setup_timer)
end
```
Client-side initialization (`init/2`):
```elixir
def init(_props, component) do
put_action(component, :start_animation)
end
```
###### Optional Initialization
Both `init/3` and `init/2` functions are optional. If you don't need to initialize state or perform any preparation, you can omit them entirely - Hologram provides default implementations that simply return the `Component` and `Server` structs unchanged.
#### Slots
Slots allow components to accept and render child content. They are defined using the `<slot />` tag in the component's template:
```elixir
defmodule Card do
use Hologram.Component
def template do
~HOLO"""
<div class="card">
<slot />
</div>
"""
end
end
```
Usage:
```holo
<Card>
<h1>Card Title</h1>
<p>Card content</p>
</Card>
```
#### Templates
##### Defining Templates
Hologram components can be templated using either a template function within the component module or a separate `.holo` file. These methods offer the same features and syntax - your choice depends on your team's coding style and project structure.
###### Template Function
```elixir
def template do
~HOLO"""
<div>Hello, {@name}!</div>
"""
end
```
###### Colocated .holo File
Create a file with the same name as your component's module file but with `.holo` extension (e.g., if your component is in `my_component.ex`, create `my_component.holo`). The `.holo` file must be located in the same directory as the module file.
Unlike the template function approach, colocated `.holo` files contain only the template markup without the `~HOLO` sigil:
```holo
<div>Hello, {@name}!</div>
```
##### Template Syntax
See the Template Syntax documentation for more details.
#### Event Handling
Stateful components can handle user interactions and business logic through two mechanisms:
- Actions: client-side operations that update local state
- Commands: server-side operations that can perform remote tasks
Example:
```elixir
def action(:increment, params, component) do
put_state(component, :count, component.state.count + params.by)
end
def command(:insert_user, params, server) do
{:ok, user} = Repo.insert(%User{first_name: params.first_name})
put_action(server, :user_inserted, user: user)
end
```
See the Actions and Commands documentation for more details.
### Pages
Pages are specialized components that serve as entry points for different routes in your Hologram application. Together with regular components, they form the fundamental building blocks of Hologram applications. They inherit all the capabilities of components, including templates, state management, actions, commands, and event handling. For detailed information about these shared features, see the Components documentation.
#### Key Differences from Regular Components
While pages are built on top of components, they have some unique characteristics:
- They must define a route using the `route/1` macro
- They must specify a layout component using either `layout/1` or `layout/2` macro, which serves as the root of the component tree and wraps the page's content (see Layouts for more information)
- They use URL parameters instead of props
- They are always stateful
- They are always initialized on the server-side using `init/3`, unlike regular components which can be initialized on either client or server
- Their `init/3` function receives URL parameters (`params`) instead of component props (`props`)
#### Basic Example
Here's a simple page implementation:
```elixir
defmodule MyApp.GreetingPage do
use Hologram.Page
route "/hello/:username"
layout MyApp.MainLayout