Debian Codegraph @

www/src/content/essays/template-fragments.md

raw symbols SCIP
1 ---
2 title: "Template Fragments"
3 description: "In this essay, Carson Gross explores the concept of template fragments, a feature in server-side rendering (SSR) that allows partial rendering of content within templates. He highlights the benefits of using template fragments in hypermedia-driven applications, providing a cleaner and more maintainable approach compared to traditional template decomposition. Carson showcases the use of template fragments in the Chill templating language and discusses how this feature improves the developer experience when working with htmx and other hypermedia-oriented libraries. He also includes examples and known implementations of template fragments in various programming languages."
4 created: 2022-08-03
5 modified: 2023-03-18
6 authors: ["Carson Gross"]
7 tags: ["guides"]
8 ---
9
10 Template fragments are a relatively rare Server Side Rendering (SSR) template library feature that allow you to render a
11 _fragment_ or partial bit of the content within a template, rather than the entire template. This feature is very handy
12 in
13 [Hypermedia Driven Applications](/essays/hypermedia-driven-applications) because it allows you to decompose a particular
14 view for partial updates _internally_ without pulling fragments of the template out to separate files for rendering,
15 creating a large number of individual template files.
16
17 By keeping all the HTML in a single file, it is also easier to reason about how a feature works. This follows the
18 [Locality of Behavior](/essays/locality-of-behaviour) design principle.
19
20 ## Motivation
21
22 Let's look at how template fragments, in an obscure templating language for java called
23 [chill templates](https://github.com/bigskysoftware/chill/tree/master/chill-script), can help us build an HDA.
24
25 Here is a simple chill template, `/contacts/detail.html` that displays a contact:
26
27 ##### /contacts/detail.html
28
29 ```html
30 <html>
31 <body>
32 <div hx-target="this">
33 #if contact.archived
34 <button hx-patch="/contacts/${contact.id}/unarchive">Unarchive</button>
35 #else
36 <button hx-delete="/contacts/${contact.id}">Archive</button>
37 #end
38 </div>
39 <h3>Contact</h3>
40 <p>${contact.email}</p>
41 </body>
42 </html>
43 ```
44
45 In the template we have an archiving feature where, depending on the archive state of the contact, we either display
46 an "Archive"
47 or an "Unarchive" button, both powered by htmx and issuing HTTP requests to different end points.
48
49 When we click whichever of the two buttons is being shown, we want to replace the content in the `div` that surrounds
50 the button with an updated button. (Note the `hx-target="this"` on the div, so we are targeting that div's innerHTML
51 for
52 replacement.) This will effectively flip the back and forth between "Archive" and "Unarchive".
53
54 Now, unfortunately, if we wanted to render only the buttons and not the rest of this template, this would typically
55 involve
56 splitting the buttons out to their own template file and including it in this template, like so:
57
58 ##### /contacts/detail.html
59
60 ```html
61 <html>
62 <body>
63 <div hx-target="this">
64 #include archive-ui.html
65 </div>
66 <h3>Contact</h3>
67 <p>${contact.email}</p>
68 </body>
69 </html>
70 ```
71
72 ##### /contacts/archive-ui.html
73
74 ```html
75 #if contact.archived
76 <button hx-patch="/contacts/${contact.id}/unarchive">Unarchive</button>
77 #else
78 <button hx-delete="/contacts/${contact.id}">Archive</button>
79 #end
80 ```
81
82 Now we have two templates. We can now render the `archive-ui.html` template separately, but this split reduces the
83 visibility of the archiving feature: it is less obvious what is going on when you are looking just at the `detail.html`
84 template.
85
86 When pushed to extremes, decomposing templates like this can lead to quite a few small template fragments which, in
87 total, become difficult to manage and to reason about.
88
89 ### Template Fragments To The Rescue
90
91 To address this issue, chill templates has a `#fragment` directive. This directive allows you to specify a block of
92 content within a template and render _just that bit of content_:
93
94 ##### /contacts/detail.html Using a Fragment
95
96 ```html
97 <html>
98 <body>
99 <div hx-target="this">
100 #fragment archive-ui
101 #if contact.archived
102 <button hx-patch="/contacts/${contact.id}/unarchive">Unarchive</button>
103 #else
104 <button hx-delete="/contacts/${contact.id}">Archive</button>
105 #end
106 #end
107 </div>
108 <h3>Contact</h3>
109 <p>${contact.email}</p>
110 </body>
111 </html>
112 ```
113
114 With this fragment defined in our template, we can now render either the entire template:
115
116 ```java
117 Contact c = getContact();
118 ChillTemplates.render("/contacts/detail.html", "contact", c);
119 ```
120
121 Or we can render only the `archive-ui` _fragment_ of the template
122
123 ```java
124 Contact c = getContact();
125 ChillTemplates.render("/contacts/detail.html#archive-ui", "contact", c);
126 ```
127
128 We would use the first option when we want to render the entire detail page for the contact.
129
130 We would use the second option when we handled the archive/unarchive actions and wished only to rerender the buttons.
131
132 Note that, with fragments, we are able to keep our UI together in a single file and see exactly what is going on with
133 the feature, without bouncing around between different template files. This provides a cleaner and more obvious
134 implementation of the feature.
135
136 ## Known Template Fragment Implementations
137
138 Fragments (and the ability to render them directly in controllers) appear to be a relatively rare feature in templating
139 libraries and provide an excellent opportunity for improving the developer experience when working with htmx and other
140 hypermedia-oriented libraries.
141
142 Here are some known implementations of the fragment concept:
143
144 * Go
145 * [Standard Library (use block actions)](https://pkg.go.dev/text/template) [[demo]](https://gist.github.com/benpate/f92b77ea9b3a8503541eb4b9eb515d8a)
146 * [templ](https://templ.guide) [[Fragment documentation]](https://templ.guide/syntax-and-usage/fragments) [[repo]](https://github.com/a-h/templ)
147 * Java
148 * [Thymeleaf](https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#fragment-specification-syntax)
149 * [Chill Templates (currently in early alpha)](https://github.com/bigskysoftware/chill/tree/master/chill-script)
150 * [Quarkus Qute](https://quarkus.io/guides/qute-reference#fragments)
151 * [JStachio (mustache)](https://jstach.io/doc/jstachio/current/apidocs/#mustache_fragments)
152 * JavaScript
153 * [Jeasx](https://www.jeasx.dev) - see [example for htmx](https://expo.jeasx.dev/fragments)
154 * PHP
155 * [Latte](https://latte.nette.org/en/template-inheritance#toc-blocks) - Use the 3rd parameter to only render 1 block
156 from the template - `$Latte_Engine->render('path/to/template.latte', [ 'foo' => 'bar' ], 'content');`
157 * [Laravel Blade](https://laravel.com/docs/10.x/blade#rendering-blade-fragments) - includes built-in support for
158 template fragments as of v9.x
159 * [Twig](https://twig.symfony.com/doc/3.x/api.html#rendering-templates) -
160 `$template->renderBlock('block_name', ['the' => 'variables', 'go' => 'here']);`
161 * Python
162 * [Django Render Block Extension](https://pypi.org/project/django-render-block/) -
163 see [example code for htmx](https://github.com/spookylukey/django-htmx-patterns/blob/master/inline_partials.rst)
164 * [jinja2-fragments package](https://github.com/sponsfreixes/jinja2-fragments)
165 * [jinja_partials package](https://github.com/mikeckennedy/jinja_partials) ([discussion](https://github.com/mikeckennedy/jinja_partials/issues/1)
166 on motivation)
167 * [chameleon_partials package](https://github.com/mikeckennedy/chameleon_partials)
168 * [htmlgenerator](https://github.com/basxsoftwareassociation/htmlgenerator)
169 * [django-template-partials](https://pypi.org/project/django-template-partials/) ([repository](https://github.com/carltongibson/django-template-partials))
170 * [django-block-fragments](https://github.com/medihack/django-block-fragments)
171 * .NET
172 * [Giraffe.ViewEngine.Htmx](https://github.com/bit-badger/Giraffe.Htmx/tree/main/src/ViewEngine.Htmx)
173 * Rust
174 * [MiniJinja](https://docs.rs/minijinja/latest/minijinja/struct.State.html#method.render_block)
175 * Raku
176 * [Cro Templates](https://github.com/croservices/cro-website/blob/main/docs/reference/cro-webapp-template-syntax.md#fragments)
177
178 Please [let me know](/discord) if you know of others, so I can add them to this list.