-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathrendering_html.cr
More file actions
1145 lines (853 loc) · 34.7 KB
/
Copy pathrendering_html.cr
File metadata and controls
1145 lines (853 loc) · 34.7 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
class Guides::Frontend::RenderingHtml < GuideAction
ANCHOR_RENDERING_TEMPLATES = "perma-rendering-templates"
ANCHOR_COMPONENTS = "perma-components"
ANCHOR_EMPTY_TAG = "perma-empty-tag"
ANCHOR_SPECIAL_TAGS = "perma-special-tags"
guide_route "/frontend/rendering-html"
def self.title
"Rendering HTML"
end
def markdown : String
<<-MD
## Intro to Lucky HTML
Lucky uses Crystal methods for rendering HTML. The Crystal methods map
as closely as possible to how HTML is used. To help with the transition
we also have a small app for [converting HTML to
Lucky methods](#{HtmlConversions::New.path}).
Using Lucky HTML adds an additional layer of type-safety, is
auto-formatted with Crystal's formatter, and can be much easier to
refactor with regular Crystal methods as HTML gets larger.
> If you still don't want to use Lucky HTML see
> [rendering templates](##{ANCHOR_RENDERING_TEMPLATES}) to learn how to use
> Lucky pages with templates files.
## Rendering a page
Let's say we have an action and we want to render all of our user's names:
```crystal
# in src/actions/users/index.cr
class Users::Index < BrowserAction
get "/users" do
# Renders the Users::IndexPage
html IndexPage, user_names: ["Paul", "Sally", "Jane"]
end
end
```
## Creating a page
Let's create the page for our `Users::Index` action. You can generate a file
quickly with `lucky gen.page Users::IndexPage`, then modify it:
```crystal
# in src/pages/users/index_page.cr
class Users::IndexPage < MainLayout
needs user_names : Array(String)
def content
ul class: "my-user-list" do
user_names.each do |name|
li name, class: "user-name"
end
end
end
end
```
Woo hoo! We created our first page. Let's walk through what's going on.
## Declaring what a page needs
You’ll notice we used `needs` near the top of the class. This declares that for
this page to render we need an Array of Strings and that they will be accessible
from the `user_names` getter method. We set the user names by passing it in the
`html` macro in our action:
```crystal
# src/actions/users/index.cr
class Users::Index < BrowserAction
get "/users" do
html IndexPage, user_names: ["Paul", "Sally", "Jane"]
end
end
```
> This is nice because you won’t accidentally forget to pass something to a page
ever again. If you forget, the compiler will tell you that you’re missing
something.
### Default values and nilable needs
Your page or component may need some value that is optional. In this case, you can
assign a default value to your `needs` or just make the type nilable. (i.e. `String?`)
```crystal
class Users::IndexPage < MainLayout
needs page : Int32 = 1
needs status : String?
def content
# `page` will always have a value
# `status` may be nil
end
end
```
From your action, you can optionally pass either of these values.
```crystal
get "/users" do
html IndexPage
# or
html IndexPage, page: 2
# or
html IndexPage, status: "active", page: 3
end
```
### Using needs with Bool
When you use a `Bool` value for `needs`, Lucky will generate a helpful
method for you that ends in `?` to denote that it will return `true` or `false`.
```crystal
class Users::IndexPage < MainLayout
needs admin : Bool = false
def content
if admin?
# ...
else
# ...
end
end
end
```
## Rendering HTML in our page
We then wrote a `content` method in our class to render our HTML. The
`content` will be rendered in your `MainLayout` (defined in
`src/pages/main_layout.cr`). Tags are generated with regular Crystal methods.
Most all HTML5 tags are available by default.
> Note that paragraph tags are `para` instead of `p` since `p` is already used
by Crystal. You can use `pp` to debug output.
### Examples of using HTML tags
```crystal
# Generate a ul tag with no other options (class, data attributes, etc), and render tags within it
ul do
li "Hey!"
end
# Generate a ul tag with options and more tags within it
ul class: "my-list", data_foo: "bar" do
li "Excellent list item"
end
# Generate a tag with the text as it's content
h1 "My cool test"
# Generate a tag with the text as content and with options
h1 "My cool test", class: "app-header"
```
Order and nesting works about the same as how you would write normal HTML.
```crystal
def content
# You can have a list
ul do
li "List item"
end
# And underneath it render something else
footer "Copyright Notice"
end
```
### Creating custom HTML tags
If you need to create a non-standard HTML tag for your application, you can use the `tag` method.
```crystal
def content
# Renders <my-custom-tag class="special control">Special</my-custom-tag>
tag("my-custom-tag", class: "special control") do
text "Special"
end
end
```
### Examples of HTML attributes
All of the HTML tag methods allow for passing in any HTML attribute.
```crystal
def content
div(id: "someID", class: "row highlight special") do
span "A special code", class: "text-note"
end
end
```
If you need to pass in data attributes, or any arbitrary attributes for use in SPAs (i.e. ng-app, ng-click, etc...), you can also use a string.
```crystal
def content
div(ng_model: "something", data_action: "someAction", "ng-click": "update")
end
```
In some cases, you find that you want to use [boolean attributes](http://w3c.github.io/html/infrastructure.html#sec-boolean-attributes) for forms or working with SPAs. For these, you just pass an `Array(Symbol)` to the `attrs` option for the tag.
```crystal
def content
# Renders <div id="application" ng-app></div>
div(id: "application", attrs: [:ng_app])
# Renders <button disabled>Click</button>
button("Click", attrs: [:disabled])
end
```
> NOTE: Lucky will automatically run attributes through a dasherize inflector. This means underscores will
> become a dash once rendered. (e.g. `:ng_app` becomes `ng-app`). In more complex cases like you see in Vuejs,
> crystal allows you to use quotes like in `:"v-on:click"`
#{permalink(ANCHOR_SPECIAL_TAGS)}
## Special tags (link, form helpers, etc.)
There are a few specials helpers that make it easier. For creating links with an
anchor tag, we have the `link` helper.
> NOTE: If you are looking for a way to create `<link>` tags in the `<head>`, use the [`empty_tag` helper](##{ANCHOR_EMPTY_TAG}).
```crystal
link "Show user", to: Users::Show.with(user.id), class: "some-html-class"
# Leave off `with` if an route doesn't need params
link "List of users", to: Users::Index
```
When you pass a route helper as we did with `Users::Show.with(user.id)`, the
link helper automatically sets the path *and* the correct HTTP verb.
Since the HTTP verb (`GET`, `POST`, `PUT`, etc.) is automatically used by `link`
we can do delete links like this:
```crystal
# data-method="delete" will automatically be set.
# This means the link submits with the right HTTP verb automatically.
link "Delete", to: Users::Delete.with(user.id)
# You can use the same nesting as with most other tags
link to: Users::Delete.with(user.id), class: "delete-link" do
img src: asset("images/delete-icon.svg")
end
```
> Since the link automatically includes the HTTP verb, you are guaranteed at
compile time that the link will go to the right place.
### Gotchas when using `link`
Crystal will search for constants (classes and modules) in the current
namespace first. This usually works fine, but there are times when Crystal
may not know how to find the correct constant. In this case you can prefix
the constant with `::` to look at the root namespace. This is best explained
with an example.
Let's say we have a nested action and a non-nested action like this:
```crystal
# Tasks nested in Projects namespace
class Projects::Tasks::Index < BrowserAction
# call the action
end
# Tasks is not nested
class Tasks::Show < BrowserAction
# call the action
end
```
Crystal will incorrectly look for `Tasks::Show` in `Projects::Tasks`:
```crystal
class Projects::Tasks::IndexPage < MainLayout
def content
# Crystal will look for Projects::Tasks::Show since it is called within
# Projects::Tasks. Crystal will see the Tasks constant and assume that's
# what we want
link "View task", Tasks::Show.with(123)
end
end
```
To fix this, prefix the call constant with `::`
```crystal
# This tells Crystal to look for the top-level Tasks constant
link "View task", ::Tasks::Show.with(123)
```
> The `link` helper method doesn't allow for a plain string path. If you need to pass a string,
> you can use the `a()` method. (e.g. `a href: "/"`).
### Rendering HTML forms
Lucky gives you lots of helper methods to make working with forms easier.
See the [rendering HTML forms](#{Guides::Frontend::HtmlForms.path}) guide to learn more.
For info on interacting with databases, see the [saving
data with operations](#{Guides::Database::SavingRecords.path(anchor: Guides::Database::SavingRecords::ANCHOR_USING_WITH_HTML_FORMS)}) guide.
#{permalink(ANCHOR_EMPTY_TAG)}
### Empty tag
If there's a bodyless tag you would like to render, but there is no helper for it, then use `empty_tag`.
```crystal
# Renders an alternative language link element:
# <link rel="alternate" hreflang="es" href="https://www.example.es/" />
empty_tag "link", rel: "alternate", hreflang: "es" href: "https://www.example.es/"
```
The first argument is a string that represents the tag name, the second is a hash passed to render as attributes.
This is especially convenient for elements with varying attributes, like a set of favicons:
```crystal
head do
# ...
empty_tag "link", rel: "apple-touch-icon", sizes: "180x180", href: "/apple-touch-icon.png"
empty_tag "link", rel: "icon", type: "image/png", sizes: "32x32", href: "/favicon-32x32.png"
empty_tag "link", rel: "icon", type: "image/png", sizes: "16x16", href: "/favicon-16x16.png"
empty_tag "link", rel: "manifest", href: "/site.webmanifest"
empty_tag "link", rel: "mask-icon", href: "/safari-pinned-tab.svg", color: "#c0ffee"
end
```
### Other special helpers
* `html_doctype` - Renders `<!DOCTYPE html>`
* `css_link(href, **options)` - Renders a `<link rel="stylesheet" media="screen">` tag with `href` and any additional/override `options`
* `js_link(src, **options)` - Renders a `<script>` tag with `src` and any additional/override `options`
* `utf8_charset` - Renders a `<meta charset="utf8">` tag
* `responsive_meta_tag` - Another meta tag for responsive design.
* `canonical_link(href)` - Renders a `<link rel="canonical" href="...">` tag.
* `nbsp(how_many = 1)` - Renders ` ` entity for the number of times in `how_many` (1 by default).
* `raw` - Render RAW string to the page.
> Note: Using `raw` can be dangerous and should **never** be used with unescaped user-generated data.
## Rendering text
Sometimes you want to render plain text. To do that use the `text` method.
> Strings rendered with `text` are automatically HTML escaped for security. Text
passed to tags is also escaped.
```crystal
div "email" do
text "This is the email text"
br
span "inbox", class: "email-tag"
end
```
### Render unescaped (raw) text
```crystal
div "email" do
# Use the `raw` method to render unescaped text
raw "·" # Render a middot HTML entity
end
```
## Inlining SVG files
Lucky allows you to inline SVG files at compile time using the `inline_svg`
macro in pages and components:
```crystal
link to: Home::Index do
inline_svg("menu/home.svg")
end
```
> The full path of the icon resolves to `src/svgs/menu/home.svg`. The svgs
> directory can be configured, as described further down in this section.
You can also omit the `.svg` extension and Lucky will resolve it automatically:
```crystal
inline_svg("menu/home")
```
By default, this macro will strip the XML declaration, comments, unnecessary
whitespace and all attributes related to styling.
> The stripped attributes are `class`, `fill`, `stroke`, `stroke-width` and
> `style`. This can also be configured.
Inlined SVGs can then be styled with CSS:
```
[data-inline-svg] {
fill: none;
stroke: '#666';
stroke-width: 1.5px;
}
```
Or with more specificity:
```
[data-inline-svg="menu/home.svg"] {
fill: pink;
}
```
In some cases, SVG may need to keep their styling attributes, like logos,
for example. By passing `false` as the second argument, the styling
attributes will remain in place:
```crystal
inline_svg("menu/logo.svg", false)
```
> Since SVGs with their original styling most likely don't require
> additional CSS styling, they have a different selector:
> `[data-inline-svg-styled]` or `[data-inline-svg-styled="menu/logo.svg"]`.
### Adding attributes to inline SVGs
You can pass arbitrary attributes to the SVG tag, which is especially useful
for accessibility attributes, class names, or data attributes:
```crystal
inline_svg("menu/home.svg", aria_hidden: true, class: "icon")
```
Attributes can be combined with the `strip_styling` flag using either
positional or named arguments:
```crystal
# Positional argument
inline_svg("menu/logo.svg", false, data_label: "logo")
# Named argument
inline_svg("menu/logo.svg", strip_styling: false, data_label: "logo")
```
> As with other Lucky HTML helpers, underscores in attribute names are
> converted to dashes. For example, `aria_hidden` becomes `aria-hidden`,
> and `data_label` becomes `data-label`.
### Configuration
Because SVGs are processed and inlined at compile time, configuration
happens through annotations. Those settings can be overridden by creating an
initializer:
```crystal
# config/svg_inliner.cr
@[Lucky::SvgInliner::Path("src/icons")]
module Lucky::SvgInliner
end
```
The example above will tell the compiler to look for SVGs in `src/icons`
rather than in the default `src/svgs`.
Another configuration option is the regular expression to strip styling
attributes. Here's an example with a regex that will only strip the `style`
and `class` attributes:
```crystal
@[Lucky::SvgInliner::StripRegex(/(class|style)="[^"]+" ?/)]
module Lucky::SvgInliner
end
```
## Finding the current page
Lucky provides the convenient `current_page?` helper on both pages and components to make it easier
to customize content based on context.
### Basic usage
`current_page?` accepts a `RouteHelper`, `Action`, or path `String`.
One common use case is to highlight the currently-viewed page in a navigation header:
```crystal
nav do
ul do
li data_current: current_page?(Home::Index) do
link "Home", to: Home::Index
end
li data_current: current_page?(Dashboard::Index) do
link "Your dashboard", to: Dashboard::Index
end
li data_current: current_page?(Me::Show) do
link "Your profile", to: Me::Show
end
end
end
```
### Advanced usage
Let's take a look at some of the additional features we can take advantage of with `current_page?`.
For example, if we are visiting `https://example.com/users?sort_by=name`:
```crystal
current_page?(Users::Index)
# => true
current_page?("/users")
# => true
current_page?("/users?sort_by=email")
# => true
current_page?("/users?sort_by=name")
# => true
current_page?("https://example.com/users")
# => true
```
We can provide an optional second argument to `current_page?`, `check_query_params`,
to tell Lucky whether or not it should care about parameters.
Let's take a look at our `https://example.com/users?sort_by=name` example from before with this new parameter in mind:
```crystal
current_page?(Users::Index, check_query_params: true)
# => true
current_page?("/users", check_query_params: true )
# => true
current_page?("/users?sort_by=email", check_query_params: true)
# => false
current_page?("/users?sort_by=name", check_query_params: true)
# => true
current_page?("https://example.com/users", check_query_params: true)
# => true
```
### Previous URL
Lucky also has a `previous_url` helper method you can use on your pages.
It returns the url of the page that issued the request (the referrer)
if possible, otherwise it uses the provided default fallback
location.
The referrer information is pulled from the 'Referer' header on
the request. This is an optional header, and if the request
is missing this header the *fallback* will be used.
Ex. within a Lucky Page, previous_url can be used to provide an href
to an anchor element that would allow the user to go back.
```crystal
a "Back", href: previous_url(fallback: Users::Index)
```
## Formatting and Page helpers
Formatting text on pages is pretty common. Lucky gives you several handy methods to help formatting.
> Some page helpers return a `String`, and some page helpers will write directly to the page.
### Converting a number to currency format
Returns a `String` formatted to a currency format.
```crystal
# Returns standard U.S. format
text number_to_currency(1234.43)
# => $1234.43
# Additional options supported for other formats
text number_to_currency(1234.32, unit: "€", separator: ",", delimiter: ".")
# => €1.234,32
```
### Truncating text
Returns a `String` truncated to `length`.
```crystal
text truncate_text("some really long text here", length: 12)
# => some real...
```
### Truncating HTML
Truncates the text, and writes HTML directly to the page.
```crystal
truncate("Four score and seven years ago", length: 20) do
link "Read more", to: President::Addresses
end
# => "Four score and se...<a href="#">Read more</a>"
```
### Highlighting text
This takes `phrases` in the form of `Array(String | Regex)` and wraps the matching phrases in a `<mark></mark>` tag.
```crystal
highlight("From this taco meat we shall eat for days!", phrases: ["taco", /eat/])
# => From this <mark>taco</mark> m<mark>eat</mark> we shall <mark>eat</mark> for days!
```
### Pluralizing a word
Returns a `String` using the first arg to determine how to pluralize the second arg.
```crystal
text "I have \#{pluralize(2, "shoe")}"
# => I have 2 shoes
```
### Wrapping words
Returns a `String`. Adds new lines (`\\n`) after the nearest word limited to `line_width`.
```crystal
word_wrap("Maybe some code would go here", line_width: 6)
# => Maybe \\nsome \\ncode \\nwould \\ngo \\nhere"
# Change the new line character with `break_sequence`.
word_wrap("Maybe some code would go here", line_width: 6, break_sequence: "<br>")
# => Maybe <br>some <br>code <br>would <br>go <br>here"
```
### Simple text format
Formats the text with some simple HTML and writes directly to the page.
```crystal
simple_format("Nice\\neasy\\nformat!")
# => <p>Nice<br>easy<br>format!</p>
```
### Sentence lists
Returns a `String`, and creates a comma-separated sentence from the provided `Enumerable` list.
```crystal
text to_sentence(["Tacos", "Burritos", "Salsa"])
# => Tacos, Burritos, and Salsa
text to_sentence(words, last_word_connector: " and ")
# => Tacos, Burritos and Salsa
```
> By default `to_sentence` will include a [serial comma](https://en.wikipedia.org/wiki/Serial_comma). Override that with the `last_word_connector` option.
### Excerpt from a paragraph
Returns a `String`. Similar to `truncate_text`, but for the middle of a large body of text.
```crystal
text excerpt("This is a beautiful morning", "beautiful", radius: 5)
# => "...is a beautiful morn..."
```
### Distance of time in words
Returns a `String` with distance in time between two `Time` objects.
```crystal
distance_of_time_in_words(Time.utc(2019, 8, 14, 10, 0, 0), Time.utc(2019, 8, 14, 10, 0, 5))
# => "5 seconds"
distance_of_time_in_words(Time.utc(2019, 8, 14, 10, 0), Time.utc(2019, 8, 14, 10, 25))
# => "25 minutes"
distance_of_time_in_words(Time.utc(2019, 8, 14, 10), Time.utc(2019, 8, 14, 11))
# => "an hour"
distance_of_time_in_words(Time.utc(2019, 8, 14), Time.utc(2019, 8, 16))
# => "2 days"
distance_of_time_in_words(Time.utc(2019, 8, 14), Time.utc(2019, 10, 4))
# => "about a month"
distance_of_time_in_words(Time.utc(2019, 8, 14), Time.utc(2061, 10, 4))
# => "almost 42 years"
```
You can also pass in a `Time::Span` object to get a String representation.
```crystal
distance_of_time_in_words(5.seconds) # => "5 seconds"
distance_of_time_in_words(25.minutes) # => "25 minutes"
distance_of_time_in_words(2.days) # => "2 days"
```
### Time ago in words
Similar to `distance_of_time_in_words`.
Returns a `String` with distance in time between current moment and some time in the past.
```crystal
time_ago_in_words(Time.utc(2019, 8, 30))
# => "about a month"
```
### Cycle values
The most common case is alternating an HTML class name between rows of data. Lucky comes with a `cycle` method that makes this much
easier to do.
```crystal
posts.each do |post|
tr class: cycle(["bg-gray-600", ""]) do
td post.title
end
end
```
In this example, the first row, and all odd rows, will be `<tr class="bg-gray-600">`, but the next row, and all even rows, will be
`<tr class="">`. You can pass as many values as you'd like to cycle through on each iteration.
## Layouts
Pages have layouts that make it easier to share common elements.
### Layouts in a default Lucky application
* `MainLayout` - The layout used when a user is signed in
* `AuthLayout` - The layout used when the user is not signed in
Pages inherit from `MainLayout`, `AuthLayout` or another layout you decide to create.
Layouts can declare [abstract
methods](https://crystal-lang.org/docs/syntax_and_semantics/virtual_and_abstract_types.html)
or use
[`responds_to?`](https://crystal-lang.org/docs/syntax_and_semantics/if_varresponds_to.html)
for more advanced page layouts.
### Rendering page specific content in the layout
Let's start with a quick example. In newly generated Lucky projects
you'll see that `MainLayout` defines a `page_title` method that is passed to
the `Shared::LayoutHeader` component. Any page that inherits from `MainLayout`
can write a new `page_title` method to override the one in `MainLayout`.
So to set a page specific title, do this:
```crystal
# src/pages/users/index_page.cr
class Users::IndexPage < MainLayout
# Override the page_title method that was originally
# defined in MainLayout
def page_title
"List of users"
end
end
```
This technique can be used to render other types of content, like a sidebar
(similar to `content_for` in Rails):
```crystal
# src/pages/main_layout.cr in the `render` method
def render
# Other layout code left out for brevity
div class: "sidebar" do
# Now pages can render content in a sidebar
render_sidebar
end
end
# This makes it so that every page needs to implement the sidebar method
# https://crystal-lang.org/docs/syntax_and_semantics/virtual_and_abstract_types.html
abstract def render_sidebar
```
Then in a page that inherits from `MainLayout`:
```crystal
class Users::IndexPage < MainLayout
def content
text "Rendering something in the main part of the layout"
end
def render_sidebar
text "This is content for the sidebar"
end
end
```
### Using `render_if_defined` in layouts for optional content
Sometimes pages have almost the same layout, but have just one or two parts
that are optional. You can handle this with
[`responds_to?`](https://crystal-lang.org/docs/syntax_and_semantics/if_varresponds_to.html)
and `render_if_defined`.
> `responds_to?` should be used when pages mostly look the same, but have just
minor changes to the layout that happen on some pages. If pages look
significantly different, consider extracting a new layout class instead.
```crystal
# Put this in a layout's `render` method
# This makes it so that pages can have an optional `help_message`.
if responds_to?(:help_section)
div class: "help-section" do
render_if_defined :help_section
end
end
# If a page has a help section, add a `help_section` method
class Admin::Users::IndexPage < MainLayout
def help_section
para "Click the 'export' button to export a CSV of all users"
end
end
```
> If you have shared HTML between multiple layouts (like a footer or
> navigation section) you can extract components to use across layouts. See
> ["Creating and using components"](##{ANCHOR_COMPONENTS})
## Extracting methods for code clarity
Extracting code for reuse or clarity is easy since pages are made of classes and
methods.
```crystal
class Users::ShowPage < MainLayout
def content
render_user_header
end
# We can extract a method to make our code easier to understand
private def render_user_header
div class: "user-header" do
h1 "Users"
link "Back to users index", to: Users::Index
end
end
end
```
#{permalink(ANCHOR_COMPONENTS)}
## Creating and using components
The most powerful and flexible way to share code is to use a Component.
Components are Crystal classes that declare what objects they need, and then
render HTML.
Let's generate one with the command `lucky gen.component Users::Row` and
fill `render`:
```crystal
# in src/components/users/row.cr
class Users::Row < BaseComponent
needs user : User
def render
div class: "user-row" do
link user.name, to: Users::Show.with(user)
end
end
end
```
Now we can mount the component in the page:
```crystal
class Users::IndexPage < MainLayout
needs user : User
def content
mount Users::Row, user: user
end
end
```
> You can also mount components from within other components in the same
> way as in pages.
### Yielding a block function to a component
You can also render a block in a component. This is helpful for when
you want have custom content injected into the component
`lucky gen.component RoundedContainer`:
```crystal
class RoundedContainer < BaseComponent
def render
div class: "rounded-container" do
yield
end
end
end
```
Now use it in a page:
```crystal
mount RoundedContainer do
h1 "This will be inside the div defined in the component"
end
```
## Sharing data used by all pages
Let's say you want to show the currently signed in user on every page in a
layout. It would be a pain to have to type `needs current_user : User` in every
page and `expose current_user: find_the_user` in every action. Lucky's got you
covered.
### Example using `needs` and `expose`
You can add `needs` to the `MainLayout` if every page that uses that layout
needs something.
For actions, we have an `expose` macro that makes it easy to automatically pass
data to rendered pages.
The `expose` macro sends the results of a method to the page, as if you had passed
it manually:
```crystal
# Without `expose`
class Users::Index < BrowserAction
get "/users" do
html IndexPage, current_user_name: current_user_name
end
private def current_user_name
"Bobby"
end
end
# The equivalent version using `expose`
class Users::Index < BrowserAction
expose current_user_name
get "/users" do
html IndexPage
end
private def current_user_name
"Bobby"
end
end
# Accessing it on all pages with `needs`
abstract class MainLayout
include Lucky::HTMLPage
needs current_user_name : String
#...
end
class Users::IndexPage < MainLayout
def content
h1 "Hello, \#{current_user_name}"
end
end
```
> `needs` will create a Crystal `getter` method by that name for you. Putting it in
> the `MainLayout` gives you access to that method on all pages.
### Full example
The best way to learn about `expose` and `needs` is to look at the default generated
actions in `src/actions` such as the `BrowserAction` in `src/actions/browser_action.cr`.
Then take a look at the layouts in `src/pages` to see how they use `needs`.
It is also helpful to look at the action mixins in `src/actions/mixins` these
declare the exposures and pipes for authentication.
#{permalink(ANCHOR_RENDERING_TEMPLATES)}
## Rendering HTML with templates (ECR, Slang, etc.)
If you are writing content heavy HTML, or just prefer templating languages
here is what you can do.
> We still recommend using Lucky HTML methods if possible. If you're having
> trouble getting started, try the [HTML to Lucky converter](#{HtmlConversions::New.path})
### Install Kilt
Add [Kilt](https://github.com/jeromegn/kilt) to your `shard.yml`