introduction.md - hugo - [fork] hugo port for 9front
HTML git clone https://git.drkhsh.at/hugo.git
DIR Log
DIR Files
DIR Refs
DIR Submodules
DIR README
DIR LICENSE
---
introduction.md (16342B)
---
1 ---
2 title: Introduction to templating
3 linkTitle: Introduction
4 description: An introduction to Hugo's templating syntax.
5 categories: []
6 keywords: []
7 weight: 10
8 ---
9
10 {{< newtemplatesystem >}}
11
12
13 {{% glossary-term template %}}
14
15 Templates use [variables], [functions], and [methods] to transform your content, resources, and data into a published page.
16
17 > [!note]
18 > Hugo uses Go's [text/template] and [html/template] packages.
19 >
20 > The text/template package implements data-driven templates for generating textual output, while the html/template package implements data-driven templates for generating HTML output safe against code injection.
21 >
22 > By default, Hugo uses the html/template package when rendering HTML files.
23
24 For example, this HTML template initializes the `$v1` and `$v2` variables, then displays them and their product within an HTML paragraph.
25
26 ```go-html-template
27 {{ $v1 := 6 }}
28 {{ $v2 := 7 }}
29 <p>The product of {{ $v1 }} and {{ $v2 }} is {{ mul $v1 $v2 }}.</p>
30 ```
31
32 While HTML templates are the most common, you can create templates for any [output format](g) including CSV, JSON, RSS, and plain text.
33
34 ## Context
35
36 The most important concept to understand before creating a template is _context_, the data passed into each template. The data may be a simple value, or more commonly [objects](g) and associated [methods](g).
37
38 For example, a template for a single page receives a `Page` object, and the `Page` object provides methods to return values or perform actions.
39
40 ### Current context
41
42 Within a template, the dot (`.`) represents the current context.
43
44 ```go-html-template {file="layouts/page.html"}
45 <h2>{{ .Title }}</h2>
46 ```
47
48 In the example above the dot represents the `Page` object, and we call its [`Title`] method to return the title as defined in [front matter].
49
50 The current context may change within a template. For example, at the top of a template the context might be a `Page` object, but we rebind the context to another value or object within [`range`] or [`with`] blocks.
51
52 ```go-html-template {file="layouts/page.html"}
53 <h2>{{ .Title }}</h2>
54
55 {{ range slice "foo" "bar" }}
56 <p>{{ . }}</p>
57 {{ end }}
58
59 {{ with "baz" }}
60 <p>{{ . }}</p>
61 {{ end }}
62 ```
63
64 In the example above, the context changes as we `range` through the [slice](g) of values. In the first iteration the context is "foo", and in the second iteration the context is "bar". Inside of the `with` block the context is "baz". Hugo renders the above to:
65
66 ```html
67 <h2>My Page Title</h2>
68 <p>foo</p>
69 <p>bar</p>
70 <p>baz</p>
71 ```
72
73 ### Template context
74
75 Within a `range` or `with` block you can access the context passed into the template by prepending a dollar sign (`$`) to the dot:
76
77 ```go-html-template {file="layouts/page.html"}
78 {{ with "foo" }}
79 <p>{{ $.Title }} - {{ . }}</p>
80 {{ end }}
81 ```
82
83 Hugo renders this to:
84
85 ```html
86 <p>My Page Title - foo</p>
87 ```
88
89 > [!note]
90 > Make sure that you thoroughly understand the concept of _context_ before you continue reading. The most common templating errors made by new users relate to context.
91
92 ## Actions
93
94 In the examples above the paired opening and closing braces represent the beginning and end of a template action, a data evaluation or control structure within a template.
95
96 A template action may contain literal values ([boolean](g), [string](g), [integer](g), and [float](g)), variables, functions, and methods.
97
98 ```go-html-template {file="layouts/page.html"}
99 {{ $convertToLower := true }}
100 {{ if $convertToLower }}
101 <h2>{{ strings.ToLower .Title }}</h2>
102 {{ end }}
103 ```
104
105 In the example above:
106
107 - `$convertToLower` is a variable
108 - `true` is a literal boolean value
109 - `strings.ToLower` is a function that converts all characters to lowercase
110 - `Title` is a method on a the `Page` object
111
112 Hugo renders the above to:
113
114 ```html
115
116
117 <h2>my page title</h2>
118
119 ```
120
121 ### Whitespace
122
123 Notice the blank lines and indentation in the previous example? Although irrelevant in production when you typically minify the output, you can remove the adjacent whitespace by using template action delimiters with hyphens:
124
125 ```go-html-template {file="layouts/page.html"}
126 {{- $convertToLower := true -}}
127 {{- if $convertToLower -}}
128 <h2>{{ strings.ToLower .Title }}</h2>
129 {{- end -}}
130 ```
131
132 Hugo renders this to:
133
134 ```html
135 <h2>my page title</h2>
136 ```
137
138 Whitespace includes spaces, horizontal tabs, carriage returns, and newlines.
139
140 ### Pipes
141
142 Within a template action you may [pipe](g) a value to a function or method. The piped value becomes the final argument to the function or method. For example, these are equivalent:
143
144 ```go-html-template
145 {{ strings.ToLower "Hugo" }} → hugo
146 {{ "Hugo" | strings.ToLower }} → hugo
147 ```
148
149 You can pipe the result of one function or method into another. For example, these are equivalent:
150
151 ```go-html-template
152 {{ strings.TrimSuffix "o" (strings.ToLower "Hugo") }} → hug
153 {{ "Hugo" | strings.ToLower | strings.TrimSuffix "o" }} → hug
154 ```
155
156 These are also equivalent:
157
158 ```go-html-template
159 {{ mul 6 (add 2 5) }} → 42
160 {{ 5 | add 2 | mul 6 }} → 42
161 ```
162
163 > [!note]
164 > Remember that the piped value becomes the final argument to the function or method to which you are piping.
165
166 ### Line splitting
167
168 You can split a template action over two or more lines. For example, these are equivalent:
169
170 ```go-html-template
171 {{ $v := or $arg1 $arg2 }}
172
173 {{ $v := or
174 $arg1
175 $arg2
176 }}
177 ```
178
179 You can also split [raw string literals](g) over two or more lines. For example, these are equivalent:
180
181 ```go-html-template
182 {{ $msg := "This is line one.\nThis is line two." }}
183
184 {{ $msg := `This is line one.
185 This is line two.`
186 }}
187 ```
188
189 ## Variables
190
191 A variable is a user-defined [identifier](g) prepended with a dollar sign (`$`), representing a value of any data type, initialized or assigned within a template action. For example, `$foo` and `$bar` are variables.
192
193 Variables may contain [scalars](g), [slices](g), [maps](g), or [objects](g).
194
195 Use `:=` to initialize a variable, and use `=` to assign a value to a variable that has been previously initialized. For example:
196
197 ```go-html-template
198 {{ $total := 3 }}
199 {{ range slice 7 11 21 }}
200 {{ $total = add $total . }}
201 {{ end }}
202 {{ $total }} → 42
203 ```
204
205 Variables initialized inside of an `if`, `range`, or `with` block are scoped to the block. Variables initialized outside of these blocks are scoped to the template.
206
207 With variables that represent a slice or map, use the [`index`] function to return the desired value.
208
209 ```go-html-template
210 {{ $slice := slice "foo" "bar" "baz" }}
211 {{ index $slice 2 }} → baz
212
213 {{ $map := dict "a" "foo" "b" "bar" "c" "baz" }}
214 {{ index $map "c" }} → baz
215 ```
216
217 > [!note]
218 > Slices and arrays are zero-based; element 0 is the first element.
219
220 With variables that represent a map or object, [chain](g) identifiers to return the desired value or to access the desired method.
221
222 ```go-html-template
223 {{ $map := dict "a" "foo" "b" "bar" "c" "baz" }}
224 {{ $map.c }} → baz
225
226 {{ $homePage := .Site.Home }}
227 {{ $homePage.Title }} → My Homepage
228 ```
229
230 > [!note]
231 > As seen above, object and method names are capitalized. Although not required, to avoid confusion we recommend beginning variable and map key names with a lowercase letter or underscore.
232
233 ## Functions
234
235 Used within a template action, a function takes one or more arguments and returns a value. Unlike methods, functions are not associated with an object.
236
237 Go's text/template and html/template packages provide a small set of functions, operators, and statements for general use. See the [go-templates] section of the function documentation for details.
238
239 Hugo provides hundreds of custom [functions] categorized by namespace. For example, the `strings` namespace includes these and other functions:
240
241 Function|Alias
242 :--|:--
243 [`strings.ToLower`](/functions/strings/tolower)|`lower`
244 [`strings.ToUpper`](/functions/strings/toupper)|`upper`
245 [`strings.Replace`](/functions/strings/replace)|`replace`
246
247 As shown above, frequently used functions have an alias. Use aliases in your templates to reduce code length.
248
249 When calling a function, separate the arguments from the function, and from each other, with a space. For example:
250
251 ```go-html-template
252 {{ $total := add 1 2 3 4 }}
253 ```
254
255 ## Methods
256
257 Used within a template action and associated with an object, a method takes zero or more arguments and either returns a value or performs an action.
258
259 The most commonly accessed objects are the [`Page`] and [`Site`] objects. This is a small sampling of the [methods] available to each object.
260
261 Object|Method|Description
262 :--|:--|:--
263 `Page`|[`Date`](methods/page/date/)|Returns the date of the given page.
264 `Page`|[`Params`](methods/page/params/)|Returns a map of custom parameters as defined in the front matter of the given page.
265 `Page`|[`Title`](methods/page/title/)|Returns the title of the given page.
266 `Site`|[`Data`](methods/site/data/)|Returns a data structure composed from the files in the `data` directory.
267 `Site`|[`Params`](methods/site/params/)|Returns a map of custom parameters as defined in the site configuration.
268 `Site`|[`Title`](methods/site/title/)|Returns the title as defined in the site configuration.
269
270 Chain the method to its object with a dot (`.`) as shown below, remembering that the leading dot represents the [current context].
271
272 ```go-html-template {file="layouts/page.html"}
273 {{ .Site.Title }} → My Site Title
274 {{ .Page.Title }} → My Page Title
275 ```
276
277 The context passed into most templates is a `Page` object, so this is equivalent to the previous example:
278
279 ```go-html-template {file="layouts/page.html"}
280 {{ .Site.Title }} → My Site Title
281 {{ .Title }} → My Page Title
282 ```
283
284 Some methods take an argument. Separate the argument from the method with a space. For example:
285
286 ```go-html-template {file="layouts/page.html"}
287 {{ $page := .Page.GetPage "/books/les-miserables" }}
288 {{ $page.Title }} → Les Misérables
289 ```
290
291 ## Comments
292
293 > [!note]
294 > Do not attempt to use HTML comment delimiters to comment out template code.
295 >
296 > Hugo strips HTML comments when rendering a page, but first evaluates any template code within the HTML comment delimiters. Depending on the template code within the HTML comment delimiters, this could cause unexpected results or fail the build.
297
298 Template comments are similar to template actions. Paired opening and closing braces represent the beginning and end of a comment. For example:
299
300 ```text
301 {{/* This is an inline comment. */}}
302 {{- /* This is an inline comment with adjacent whitespace removed. */ -}}
303 ```
304
305 Code within a comment is not parsed, executed, or displayed. Comments may be inline, as shown above, or in block form:
306
307 ```text
308 {{/*
309 This is a block comment.
310 */}}
311
312 {{- /*
313 This is a block comment with
314 adjacent whitespace removed.
315 */ -}}
316 ```
317
318 You may not nest one comment inside of another.
319
320 To render an HTML comment, pass a string through the [`safeHTML`] template function. For example:
321
322 ```go-html-template
323 {{ "<!-- I am an HTML comment. -->" | safeHTML }}
324 {{ printf "<!-- This is the %s site. -->" .Site.Title | safeHTML }}
325 ```
326
327 ## Include
328
329 Use the [`template`] function to include one or more of Hugo's [embedded templates]:
330
331 ```go-html-template
332 {{ partial "google_analytics.html" . }}
333 {{ partial "opengraph" . }}
334 {{ partial "pagination.html" . }}
335 {{ partial "schema.html" . }}
336 {{ partial "twitter_cards.html" . }}
337 ```
338
339 Use the [`partial`] or [`partialCached`] function to include one or more [partial templates]:
340
341 ```go-html-template
342 {{ partial "breadcrumbs.html" . }}
343 {{ partialCached "css.html" . }}
344 ```
345
346 Create your partial templates in the layouts/_partials directory.
347
348 > [!note]
349 > In the examples above, note that we are passing the current context (the dot) to each of the templates.
350
351 ## Examples
352
353 This limited set of contrived examples demonstrates some of concepts described above. Please see the [functions], [methods], and [templates] documentation for specific examples.
354
355 ### Conditional blocks
356
357 See documentation for [`if`], [`else`], and [`end`].
358
359 ```go-html-template
360 {{ $var := 42 }}
361 {{ if eq $var 6 }}
362 {{ print "var is 6" }}
363 {{ else if eq $var 7 }}
364 {{ print "var is 7" }}
365 {{ else if eq $var 42 }}
366 {{ print "var is 42" }}
367 {{ else }}
368 {{ print "var is something else" }}
369 {{ end }}
370 ```
371
372 ### Logical operators
373
374 See documentation for [`and`] and [`or`].
375
376 ```go-html-template
377 {{ $v1 := true }}
378 {{ $v2 := false }}
379 {{ $v3 := false }}
380 {{ $result := false }}
381
382 {{ if and $v1 $v2 $v3 }}
383 {{ $result = true }}
384 {{ end }}
385 {{ $result }} → false
386
387 {{ if or $v1 $v2 $v3 }}
388 {{ $result = true }}
389 {{ end }}
390 {{ $result }} → true
391 ```
392
393 ### Loops
394
395 See documentation for [`range`], [`else`], and [`end`].
396
397 ```go-html-template
398 {{ $s := slice "foo" "bar" "baz" }}
399 {{ range $s }}
400 <p>{{ . }}</p>
401 {{ else }}
402 <p>The collection is empty</p>
403 {{ end }}
404 ```
405
406 To loop a specified number of times:
407
408 ```go-html-template
409 {{ $s := slice }}
410 {{ range 3 }}
411 {{ $s = $s | append . }}
412 {{ end }}
413 {{ $s }} → [0 1 2]
414 ```
415
416 ### Rebind context
417
418 See documentation for [`with`], [`else`], and [`end`].
419
420 ```go-html-template
421 {{ $var := "foo" }}
422 {{ with $var }}
423 {{ . }} → foo
424 {{ else }}
425 {{ print "var is falsy" }}
426 {{ end }}
427 ```
428
429 To test multiple conditions:
430
431 ```go-html-template
432 {{ $v1 := 0 }}
433 {{ $v2 := 42 }}
434 {{ with $v1 }}
435 {{ . }}
436 {{ else with $v2 }}
437 {{ . }} → 42
438 {{ else }}
439 {{ print "v1 and v2 are falsy" }}
440 {{ end }}
441 ```
442
443 ### Access site parameters
444
445 See documentation for the [`Params`](/methods/site/params/) method on a `Site` object.
446
447 With this site configuration:
448
449 {{< code-toggle file=hugo >}}
450 title = 'ABC Widgets'
451 baseURL = 'https://example.org'
452 [params]
453 subtitle = 'The Best Widgets on Earth'
454 copyright-year = '2023'
455 [params.author]
456 email = 'jsmith@example.org'
457 name = 'John Smith'
458 [params.layouts]
459 rfc_1123 = 'Mon, 02 Jan 2006 15:04:05 MST'
460 rfc_3339 = '2006-01-02T15:04:05-07:00'
461 {{< /code-toggle >}}
462
463 Access the custom site parameters by chaining the identifiers:
464
465 ```go-html-template
466 {{ .Site.Params.subtitle }} → The Best Widgets on Earth
467 {{ .Site.Params.author.name }} → John Smith
468
469 {{ $layout := .Site.Params.layouts.rfc_1123 }}
470 {{ .Site.Lastmod.Format $layout }} → Tue, 17 Oct 2023 13:21:02 PDT
471 ```
472
473 ### Access page parameters
474
475 See documentation for the [`Params`](/methods/page/params/) method on a `Page` object.
476
477 By way of example, consider this front matter:
478
479 {{< code-toggle file=content/annual-conference.md fm=true >}}
480 title = 'Annual conference'
481 date = 2023-10-17T15:11:37-07:00
482 [params]
483 display_related = true
484 key-with-hyphens = 'must use index function'
485 [params.author]
486 email = 'jsmith@example.org'
487 name = 'John Smith'
488 {{< /code-toggle >}}
489
490 The `title` and `date` fields are standard [front matter fields], while the other fields are user-defined.
491
492 Access the custom fields by [chaining](g) the [identifiers](g) when needed:
493
494 ```go-html-template
495 {{ .Params.display_related }} → true
496 {{ .Params.author.email }} → jsmith@example.org
497 {{ .Params.author.name }} → John Smith
498 ```
499
500 In the template example above, each of the keys is a valid identifier. For example, none of the keys contains a hyphen. To access a key that is not a valid identifier, use the [`index`] function:
501
502 ```go-html-template
503 {{ index .Params "key-with-hyphens" }} → must use index function
504 ```
505
506 [`and`]: /functions/go-template/and
507 [`else`]: /functions/go-template/else/
508 [`end`]: /functions/go-template/end/
509 [`if`]: /functions/go-template/if/
510 [`index`]: /functions/collections/indexfunction/
511 [`index`]: /functions/collections/indexfunction/
512 [`or`]: /functions/go-template/or
513 [`Page`]: /methods/page/
514 [`partial`]: /functions/partials/include/
515 [`partialCached`]: /functions/partials/includecached/
516 [`range`]: /functions/go-template/range/
517 [`range`]: /functions/go-template/range/
518 [`safeHTML`]: /functions/safe/html
519 [`Site`]: /methods/site/
520 [`template`]: /functions/go-template/template/
521 [`Title`]: /methods/page/title
522 [`with`]: /functions/go-template/with/
523 [`with`]: /functions/go-template/with/
524 [current context]: #current-context
525 [embedded templates]: /templates/embedded/
526 [front matter]: /content-management/front-matter/
527 [front matter fields]: /content-management/front-matter/#fields
528 [functions]: /functions/
529 [functions]: /functions
530 [go-templates]: /functions/go-template/
531 [html/template]: https://pkg.go.dev/html/template
532 [methods]: /methods/
533 [methods]: /methods/
534 [partial templates]: /templates/types/#partial
535 [templates]: /templates/
536 [text/template]: https://pkg.go.dev/text/template
537 [variables]: #variables