Debian Codegraph @

docs/content/en/templates/introduction.md

raw
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 {{% glossary-term template %}}
13
14 Templates use [variables](#variables), [functions][], and [methods][] to transform your content, resources, and data into a published page.
15
16 > [!NOTE]
17 > Hugo uses Go's [`text/template`][] and [`html/template`][] packages.
18 >
19 > 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.
20 >
21 > By default, Hugo uses the `html/template` package when rendering HTML files.
22
23 For example, this HTML template initializes the `$v1` and `$v2` variables, then displays them and their product within an HTML paragraph.
24
25 ```go-html-template
26 {{ $v1 := 6 }}
27 {{ $v2 := 7 }}
28 <p>The product of {{ $v1 }} and {{ $v2 }} is {{ mul $v1 $v2 }}.</p>
29 ```
30
31 While HTML templates are the most common, you can create templates for any [output format](g) including CSV, JSON, RSS, and plain text.
32
33 ## Context
34
35 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).
36
37 For example, a _page_ template receives a `Page` object, and the `Page` object provides methods to return values or perform actions.
38
39 ### Current context
40
41 Within a template, the dot (`.`) represents the current context.
42
43 ```go-html-template {file="layouts/page.html"}
44 <h2>{{ .Title }}</h2>
45 ```
46
47 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][].
48
49 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.
50
51 ```go-html-template {file="layouts/page.html"}
52 <h2>{{ .Title }}</h2>
53
54 {{ range slice "foo" "bar" }}
55 <p>{{ . }}</p>
56 {{ end }}
57
58 {{ with "baz" }}
59 <p>{{ . }}</p>
60 {{ end }}
61 ```
62
63 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:
64
65 ```html
66 <h2>My Page Title</h2>
67 <p>foo</p>
68 <p>bar</p>
69 <p>baz</p>
70 ```
71
72 ### Template context
73
74 Within a `range` or `with` block you can access the context passed into the template by prepending a dollar sign (`$`) to the dot:
75
76 ```go-html-template {file="layouts/page.html"}
77 {{ with "foo" }}
78 <p>{{ $.Title }} - {{ . }}</p>
79 {{ end }}
80 ```
81
82 Hugo renders this to:
83
84 ```html
85 <p>My Page Title - foo</p>
86 ```
87
88 > [!NOTE]
89 > 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.
90
91 ## Actions
92
93 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.
94
95 A template action may contain literal values ([boolean](g), [string](g), [integer](g), and [float](g)), the [current context](#current-context), [variables](#variables), [functions](#functions), [methods](#methods), and the [`nil`](#nil) keyword.
96
97 ```go-html-template {file="layouts/page.html"}
98 {{ $convertToLower := true }}
99 {{ if $convertToLower }}
100 <h2>{{ strings.ToLower .Title }}</h2>
101 {{ end }}
102 ```
103
104 In the example above:
105
106 - `$convertToLower` is a variable
107 - `true` is a literal boolean value
108 - `if` is the beginning of a control structure
109 - `strings.ToLower` is a function that converts all characters to lowercase
110 - `Title` is a method on a the `Page` object
111 - `end` is the end of a control structure
112
113 Hugo renders the above to:
114
115 ```html {trim=false}
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 ### Quote characters
141
142 Hugo templates use different quote characters to define how text and characters are processed.
143
144 Use double quotes for [interpreted string literals](g). These interpret backslashes as special instructions:
145
146 ```go-html-template
147 {{ print "Hello world\u0021" }} → Hello world!
148 ```
149
150 Use backticks for [raw string literals](g). These ignore backslashes and treat every character literally:
151
152 ```go-html-template
153 {{ print `Hello world\u0021` }} → Hello world\u0021
154 ```
155
156 Use single quotes for [rune literals](g). Unlike strings, these represent a single character as its numerical Unicode value:
157
158 ```go-html-template
159 {{ print '!' }} → 33
160 ```
161
162 In practical terms, you will rarely, if ever, use rune literals in your template code. They are most commonly used in low-level programming; in a Hugo template, you will almost always want a string instead.
163
164 ### Pipes
165
166 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:
167
168 ```go-html-template
169 {{ strings.ToLower "Hugo" }} → hugo
170 {{ "Hugo" | strings.ToLower }} → hugo
171 ```
172
173 You can pipe the result of one function or method into another. For example, these are equivalent:
174
175 ```go-html-template
176 {{ strings.TrimSuffix "o" (strings.ToLower "Hugo") }} → hug
177 {{ "Hugo" | strings.ToLower | strings.TrimSuffix "o" }} → hug
178 ```
179
180 These are also equivalent:
181
182 ```go-html-template
183 {{ mul 6 (add 2 5) }} → 42
184 {{ 5 | add 2 | mul 6 }} → 42
185 ```
186
187 > [!NOTE]
188 > Remember that the piped value becomes the final argument to the function or method to which you are piping.
189
190 ### Line splitting
191
192 You can split a template action over two or more lines. For example, these are equivalent:
193
194 ```go-html-template
195 {{ $v := or $arg1 $arg2 }}
196
197 {{ $v := or
198 $arg1
199 $arg2
200 }}
201 ```
202
203 You can also split [raw string literals](g) over two or more lines. For example, these are equivalent:
204
205 ```go-html-template
206 {{ $msg := "This is line one.\nThis is line two." }}
207
208 {{ $msg := `This is line one.
209 This is line two.`
210 }}
211 ```
212
213 ### Nil
214
215 Other than using the `nil` keyword in comparisons, you may not use it as an argument to any function or method, nor may you assign it to a variable. For example, these are valid uses of the `nil` keyword:
216
217 ```go-html-template
218 {{ if gt 42 nil }}
219 <p>42 is greater than nil</p>
220 {{ end }}
221
222 {{ $pages := where .Site.RegularPages "Params.color" "ne" nil }}
223 ```
224
225 These, on the other hand, are invalid:
226
227 ```go-html-template
228 {{ $a := nil }}
229 {{ add 3 nil }}
230 {{ nil | print}}
231 ```
232
233 The actions above throw an error.
234
235 ## Variables
236
237 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.
238
239 Variables may contain [scalars](g), [slices](g), [maps](g), or [objects](g).
240
241 Use `:=` to initialize a variable, and use `=` to assign a value to a variable that has been previously initialized. For example:
242
243 ```go-html-template
244 {{ $total := 3 }}
245 {{ range slice 7 11 21 }}
246 {{ $total = add $total . }}
247 {{ end }}
248 {{ $total }} → 42
249 ```
250
251 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.
252
253 With variables that represent a slice or map, use the [`index`][] function to return the desired value.
254
255 ```go-html-template
256 {{ $slice := slice "foo" "bar" "baz" }}
257 {{ index $slice 2 }} → baz
258
259 {{ $map := dict "a" "foo" "b" "bar" "c" "baz" }}
260 {{ index $map "c" }} → baz
261 ```
262
263 > [!NOTE]
264 > Slices and arrays are zero-based; element 0 is the first element.
265
266 With variables that represent a map or object, [chain](g) identifiers to return the desired value or to access the desired method.
267
268 ```go-html-template
269 {{ $map := dict "a" "foo" "b" "bar" "c" "baz" }}
270 {{ $map.c }} → baz
271
272 {{ $homePage := .Site.Home }}
273 {{ $homePage.Title }} → My Homepage
274 ```
275
276 > [!NOTE]
277 > 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.
278
279 ## Functions
280
281 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.
282
283 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.
284
285 Hugo provides hundreds of custom [functions][] categorized by namespace. For example, the `strings` namespace includes these and other functions:
286
287 Function|Alias
288 :--|:--
289 [`strings.ToLower`][]|`lower`
290 [`strings.ToUpper`][]|`upper`
291 [`strings.Replace`][]|`replace`
292
293 As shown above, frequently used functions have an alias. Use aliases in your templates to reduce code length. For example, these are equivalent:
294
295 ```go-html-template
296 {{ strings.ToLower "Hugo" }} → hugo
297 {{ lower "Hugo" }} → hugo
298 ```
299
300 When calling a function, separate the arguments from the function, and from each other, with a space. For example:
301
302 ```go-html-template
303 {{ $total := add 1 2 3 4 }}
304 ```
305
306 ## Methods
307
308 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.
309
310 The most commonly accessed objects are the [`Page`][] and [`Site`][] objects. This is a small sampling of the [methods][] available to each object.
311
312 Object|Method|Description
313 :--|:--|:--
314 `Page`|[`Date`](methods/page/date/)|Returns the date of the given page.
315 `Page`|[`Params`](methods/page/params/)|Returns a map of custom parameters as defined in the front matter of the given page.
316 `Page`|[`Title`](methods/page/title/)|Returns the title of the given page.
317 `Site`|[`Data`](methods/site/data/)|Returns a data structure composed from the files in the `data` directory.
318 `Site`|[`Params`](methods/site/params/)|Returns a map of custom parameters as defined in your project configuration.
319 `Site`|[`Title`](methods/site/title/)|Returns the title as defined in the your project configuration.
320
321 Chain the method to its object with a dot (`.`) as shown below, remembering that the leading dot represents the [current context](#current-context).
322
323 ```go-html-template {file="layouts/page.html"}
324 {{ .Site.Title }} → My Site Title
325 {{ .Page.Title }} → My Page Title
326 ```
327
328 The context passed into most templates is a `Page` object, so this is equivalent to the previous example:
329
330 ```go-html-template {file="layouts/page.html"}
331 {{ .Site.Title }} → My Site Title
332 {{ .Title }} → My Page Title
333 ```
334
335 Some methods take an argument. Separate the argument from the method with a space. For example:
336
337 ```go-html-template {file="layouts/page.html"}
338 {{ $page := .Page.GetPage "/books/les-miserables" }}
339 {{ $page.Title }} → Les Misérables
340 ```
341
342 ## Comments
343
344 > [!NOTE]
345 > Do not attempt to use HTML comment delimiters to comment out template code.
346 >
347 > 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.
348
349 Template comments are similar to template actions. Paired opening and closing braces represent the beginning and end of a comment. For example:
350
351 ```go-html-template
352 {{/* This is an inline comment. */}}
353 {{- /* This is an inline comment with adjacent whitespace removed. */ -}}
354 ```
355
356 Code within a comment is not parsed, executed, or displayed. Comments may be inline, as shown above, or in block form:
357
358 ```go-html-template
359 {{/*
360 This is a block comment.
361 */}}
362
363 {{- /*
364 This is a block comment with
365 adjacent whitespace removed.
366 */ -}}
367 ```
368
369 You may not nest one comment inside of another.
370
371 To render an HTML comment, pass a string through the [`safe.HTML`][] function. For example:
372
373 ```go-html-template
374 {{ "<!-- I am an HTML comment. -->" | safeHTML }}
375 {{ printf "<!-- This is the %s site. -->" .Site.Title | safeHTML }}
376 ```
377
378 ## Include
379
380 Use the [`template`][] function to include one or more of Hugo's [embedded templates][]:
381
382 ```go-html-template
383 {{ partial "google_analytics.html" . }}
384 {{ partial "opengraph" . }}
385 {{ partial "pagination.html" . }}
386 {{ partial "schema.html" . }}
387 {{ partial "twitter_cards.html" . }}
388 ```
389
390 Use the [`partial`][] or [`partialCached`][] function to include one or more [partial templates][]:
391
392 ```go-html-template
393 {{ partial "breadcrumbs.html" . }}
394 {{ partialCached "css.html" . }}
395 ```
396
397 Create your _partial_ templates in the `layouts/_partials` directory.
398
399 > [!NOTE]
400 > In the examples above, note that we are passing the current context (the dot) to each of the templates.
401
402 ## Examples
403
404 This limited set of contrived examples demonstrates some of concepts described above. Please see the [functions][], [methods][], and [templates][] documentation for specific examples.
405
406 ### Conditional blocks
407
408 See documentation for [`if`][], [`else`][], and [`end`][].
409
410 ```go-html-template
411 {{ $var := 42 }}
412 {{ if eq $var 6 }}
413 {{ print "var is 6" }}
414 {{ else if eq $var 7 }}
415 {{ print "var is 7" }}
416 {{ else if eq $var 42 }}
417 {{ print "var is 42" }}
418 {{ else }}
419 {{ print "var is something else" }}
420 {{ end }}
421 ```
422
423 ### Logical operators
424
425 See documentation for [`and`][] and [`or`][].
426
427 ```go-html-template
428 {{ $v1 := true }}
429 {{ $v2 := false }}
430 {{ $v3 := false }}
431 {{ $result := false }}
432
433 {{ if and $v1 $v2 $v3 }}
434 {{ $result = true }}
435 {{ end }}
436 {{ $result }} → false
437
438 {{ if or $v1 $v2 $v3 }}
439 {{ $result = true }}
440 {{ end }}
441 {{ $result }} → true
442 ```
443
444 ### Loops
445
446 See documentation for [`range`][], [`else`][], and [`end`][].
447
448 ```go-html-template
449 {{ $s := slice "foo" "bar" "baz" }}
450 {{ range $s }}
451 <p>{{ . }}</p>
452 {{ else }}
453 <p>The collection is empty</p>
454 {{ end }}
455 ```
456
457 To loop a specified number of times:
458
459 ```go-html-template
460 {{ $s := slice }}
461 {{ range 3 }}
462 {{ $s = $s | append . }}
463 {{ end }}
464 {{ $s }} → [0 1 2]
465 ```
466
467 ### Rebind context
468
469 See documentation for [`with`][], [`else`][], and [`end`][].
470
471 ```go-html-template
472 {{ $var := "foo" }}
473 {{ with $var }}
474 {{ . }} → foo
475 {{ else }}
476 {{ print "var is falsy" }}
477 {{ end }}
478 ```
479
480 To test multiple conditions:
481
482 ```go-html-template
483 {{ $v1 := 0 }}
484 {{ $v2 := 42 }}
485 {{ with $v1 }}
486 {{ . }}
487 {{ else with $v2 }}
488 {{ . }} → 42
489 {{ else }}
490 {{ print "v1 and v2 are falsy" }}
491 {{ end }}
492 ```
493
494 ### Access site parameters
495
496 See documentation for the [`Params`][params_site] method on a `Site` object.
497
498 With this project configuration:
499
500 {{< code-toggle file=hugo >}}
501 title = 'ABC Widgets'
502 baseURL = 'https://example.org'
503 [params]
504 subtitle = 'The Best Widgets on Earth'
505 copyright-year = '2023'
506 [params.author]
507 email = '[email protected]'
508 name = 'John Smith'
509 [params.layouts]
510 rfc_1123 = 'Mon, 02 Jan 2006 15:04:05 MST'
511 rfc_3339 = '2006-01-02T15:04:05-07:00'
512 {{< /code-toggle >}}
513
514 Access the custom site parameters by chaining the identifiers:
515
516 ```go-html-template
517 {{ .Site.Params.subtitle }} → The Best Widgets on Earth
518 {{ .Site.Params.author.name }} → John Smith
519
520 {{ $layout := .Site.Params.layouts.rfc_1123 }}
521 {{ .Site.Lastmod.Format $layout }} → Tue, 17 Oct 2023 13:21:02 PDT
522 ```
523
524 ### Access page parameters
525
526 See documentation for the [`Params`][params_page] method on a `Page` object.
527
528 By way of example, consider this front matter:
529
530 {{< code-toggle file=content/annual-conference.md fm=true >}}
531 title = 'Annual conference'
532 date = 2023-10-17T15:11:37-07:00
533 [params]
534 display_related = true
535 key-with-hyphens = 'must use index function'
536 [params.author]
537 email = '[email protected]'
538 name = 'John Smith'
539 {{< /code-toggle >}}
540
541 The `title` and `date` fields are standard [front matter fields][], while the other fields are user-defined.
542
543 Access the custom fields by [chaining](g) the [identifiers](g) when needed:
544
545 ```go-html-template
546 {{ .Params.display_related }} → true
547 {{ .Params.author.email }} → [email protected]
548 {{ .Params.author.name }} → John Smith
549 ```
550
551 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:
552
553 ```go-html-template
554 {{ index .Params "key-with-hyphens" }} → must use index function
555 ```
556
557 [`Page`]: /methods/page/
558 [`Site`]: /methods/site/
559 [`Title`]: /methods/page/title/
560 [`and`]: /functions/go-template/and/
561 [`else`]: /functions/go-template/else/
562 [`end`]: /functions/go-template/end/
563 [`html/template`]: https://pkg.go.dev/html/template
564 [`if`]: /functions/go-template/if/
565 [`index`]: /functions/collections/indexfunction/
566 [`or`]: /functions/go-template/or/
567 [`partialCached`]: /functions/partials/includecached/
568 [`partial`]: /functions/partials/include/
569 [`range`]: /functions/go-template/range/
570 [`safe.HTML`]: /functions/safe/html/
571 [`strings.Replace`]: /functions/strings/replace/
572 [`strings.ToLower`]: /functions/strings/tolower/
573 [`strings.ToUpper`]: /functions/strings/toupper/
574 [`template`]: /functions/go-template/template/
575 [`text/template`]: https://pkg.go.dev/text/template
576 [`with`]: /functions/go-template/with/
577 [embedded templates]: /templates/embedded/
578 [front matter fields]: /content-management/front-matter/#fields
579 [front matter]: /content-management/front-matter/
580 [functions]: /functions/
581 [go-templates]: /functions/go-template/
582 [methods]: /methods/
583 [params_page]: /methods/page/params/
584 [params_site]: /methods/site/params/
585 [partial templates]: /templates/types/#partial
586 [templates]: /templates/