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.
294
295 When calling a function, separate the arguments from the function, and from each other, with a space. For example:
296
297 ```go-html-template
298 {{ $total := add 1 2 3 4 }}
299 ```
300
301 ## Methods
302
303 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.
304
305 The most commonly accessed objects are the [`Page`][] and [`Site`][] objects. This is a small sampling of the [methods][] available to each object.
306
307 Object|Method|Description
308 :--|:--|:--
309 `Page`|[`Date`](methods/page/date/)|Returns the date of the given page.
310 `Page`|[`Params`](methods/page/params/)|Returns a map of custom parameters as defined in the front matter of the given page.
311 `Page`|[`Title`](methods/page/title/)|Returns the title of the given page.
312 `Site`|[`Data`](methods/site/data/)|Returns a data structure composed from the files in the `data` directory.
313 `Site`|[`Params`](methods/site/params/)|Returns a map of custom parameters as defined in your project configuration.
314 `Site`|[`Title`](methods/site/title/)|Returns the title as defined in the your project configuration.
315
316 Chain the method to its object with a dot (`.`) as shown below, remembering that the leading dot represents the [current context](#current-context).
317
318 ```go-html-template {file="layouts/page.html"}
319 {{ .Site.Title }} → My Site Title
320 {{ .Page.Title }} → My Page Title
321 ```
322
323 The context passed into most templates is a `Page` object, so this is equivalent to the previous example:
324
325 ```go-html-template {file="layouts/page.html"}
326 {{ .Site.Title }} → My Site Title
327 {{ .Title }} → My Page Title
328 ```
329
330 Some methods take an argument. Separate the argument from the method with a space. For example:
331
332 ```go-html-template {file="layouts/page.html"}
333 {{ $page := .Page.GetPage "/books/les-miserables" }}
334 {{ $page.Title }} → Les Misérables
335 ```
336
337 ## Comments
338
339 > [!NOTE]
340 > Do not attempt to use HTML comment delimiters to comment out template code.
341 >
342 > 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.
343
344 Template comments are similar to template actions. Paired opening and closing braces represent the beginning and end of a comment. For example:
345
346 ```go-html-template
347 {{/* This is an inline comment. */}}
348 {{- /* This is an inline comment with adjacent whitespace removed. */ -}}
349 ```
350
351 Code within a comment is not parsed, executed, or displayed. Comments may be inline, as shown above, or in block form:
352
353 ```go-html-template
354 {{/*
355 This is a block comment.
356 */}}
357
358 {{- /*
359 This is a block comment with
360 adjacent whitespace removed.
361 */ -}}
362 ```
363
364 You may not nest one comment inside of another.
365
366 To render an HTML comment, pass a string through the [`safe.HTML`][] function. For example:
367
368 ```go-html-template
369 {{ "<!-- I am an HTML comment. -->" | safeHTML }}
370 {{ printf "<!-- This is the %s site. -->" .Site.Title | safeHTML }}
371 ```
372
373 ## Include
374
375 Use the [`template`][] function to include one or more of Hugo's [embedded templates][]:
376
377 ```go-html-template
378 {{ partial "google_analytics.html" . }}
379 {{ partial "opengraph" . }}
380 {{ partial "pagination.html" . }}
381 {{ partial "schema.html" . }}
382 {{ partial "twitter_cards.html" . }}
383 ```
384
385 Use the [`partial`][] or [`partialCached`][] function to include one or more [partial templates][]:
386
387 ```go-html-template
388 {{ partial "breadcrumbs.html" . }}
389 {{ partialCached "css.html" . }}
390 ```
391
392 Create your _partial_ templates in the `layouts/_partials` directory.
393
394 > [!NOTE]
395 > In the examples above, note that we are passing the current context (the dot) to each of the templates.
396
397 ## Examples
398
399 This limited set of contrived examples demonstrates some of concepts described above. Please see the [functions][], [methods][], and [templates][] documentation for specific examples.
400
401 ### Conditional blocks
402
403 See documentation for [`if`][], [`else`][], and [`end`][].
404
405 ```go-html-template
406 {{ $var := 42 }}
407 {{ if eq $var 6 }}
408 {{ print "var is 6" }}
409 {{ else if eq $var 7 }}
410 {{ print "var is 7" }}
411 {{ else if eq $var 42 }}
412 {{ print "var is 42" }}
413 {{ else }}
414 {{ print "var is something else" }}
415 {{ end }}
416 ```
417
418 ### Logical operators
419
420 See documentation for [`and`][] and [`or`][].
421
422 ```go-html-template
423 {{ $v1 := true }}
424 {{ $v2 := false }}
425 {{ $v3 := false }}
426 {{ $result := false }}
427
428 {{ if and $v1 $v2 $v3 }}
429 {{ $result = true }}
430 {{ end }}
431 {{ $result }} → false
432
433 {{ if or $v1 $v2 $v3 }}
434 {{ $result = true }}
435 {{ end }}
436 {{ $result }} → true
437 ```
438
439 ### Loops
440
441 See documentation for [`range`][], [`else`][], and [`end`][].
442
443 ```go-html-template
444 {{ $s := slice "foo" "bar" "baz" }}
445 {{ range $s }}
446 <p>{{ . }}</p>
447 {{ else }}
448 <p>The collection is empty</p>
449 {{ end }}
450 ```
451
452 To loop a specified number of times:
453
454 ```go-html-template
455 {{ $s := slice }}
456 {{ range 3 }}
457 {{ $s = $s | append . }}
458 {{ end }}
459 {{ $s }} → [0 1 2]
460 ```
461
462 ### Rebind context
463
464 See documentation for [`with`][], [`else`][], and [`end`][].
465
466 ```go-html-template
467 {{ $var := "foo" }}
468 {{ with $var }}
469 {{ . }} → foo
470 {{ else }}
471 {{ print "var is falsy" }}
472 {{ end }}
473 ```
474
475 To test multiple conditions:
476
477 ```go-html-template
478 {{ $v1 := 0 }}
479 {{ $v2 := 42 }}
480 {{ with $v1 }}
481 {{ . }}
482 {{ else with $v2 }}
483 {{ . }} → 42
484 {{ else }}
485 {{ print "v1 and v2 are falsy" }}
486 {{ end }}
487 ```
488
489 ### Access site parameters
490
491 See documentation for the [`Params`][params_site] method on a `Site` object.
492
493 With this project configuration:
494
495 {{< code-toggle file=hugo >}}
496 title = 'ABC Widgets'
497 baseURL = 'https://example.org'
498 [params]
499 subtitle = 'The Best Widgets on Earth'
500 copyright-year = '2023'
501 [params.author]
502 email = '[email protected]'
503 name = 'John Smith'
504 [params.layouts]
505 rfc_1123 = 'Mon, 02 Jan 2006 15:04:05 MST'
506 rfc_3339 = '2006-01-02T15:04:05-07:00'
507 {{< /code-toggle >}}
508
509 Access the custom site parameters by chaining the identifiers:
510
511 ```go-html-template
512 {{ .Site.Params.subtitle }} → The Best Widgets on Earth
513 {{ .Site.Params.author.name }} → John Smith
514
515 {{ $layout := .Site.Params.layouts.rfc_1123 }}
516 {{ .Site.Lastmod.Format $layout }} → Tue, 17 Oct 2023 13:21:02 PDT
517 ```
518
519 ### Access page parameters
520
521 See documentation for the [`Params`][params_page] method on a `Page` object.
522
523 By way of example, consider this front matter:
524
525 {{< code-toggle file=content/annual-conference.md fm=true >}}
526 title = 'Annual conference'
527 date = 2023-10-17T15:11:37-07:00
528 [params]
529 display_related = true
530 key-with-hyphens = 'must use index function'
531 [params.author]
532 email = '[email protected]'
533 name = 'John Smith'
534 {{< /code-toggle >}}
535
536 The `title` and `date` fields are standard [front matter fields][], while the other fields are user-defined.
537
538 Access the custom fields by [chaining](g) the [identifiers](g) when needed:
539
540 ```go-html-template
541 {{ .Params.display_related }} → true
542 {{ .Params.author.email }} → [email protected]
543 {{ .Params.author.name }} → John Smith
544 ```
545
546 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:
547
548 ```go-html-template
549 {{ index .Params "key-with-hyphens" }} → must use index function
550 ```
551
552 [`Page`]: /methods/page/
553 [`Site`]: /methods/site/
554 [`Title`]: /methods/page/title/
555 [`and`]: /functions/go-template/and/
556 [`else`]: /functions/go-template/else/
557 [`end`]: /functions/go-template/end/
558 [`html/template`]: https://pkg.go.dev/html/template
559 [`if`]: /functions/go-template/if/
560 [`index`]: /functions/collections/indexfunction/
561 [`or`]: /functions/go-template/or/
562 [`partialCached`]: /functions/partials/includecached/
563 [`partial`]: /functions/partials/include/
564 [`range`]: /functions/go-template/range/
565 [`safe.HTML`]: /functions/safe/html/
566 [`strings.Replace`]: /functions/strings/replace/
567 [`strings.ToLower`]: /functions/strings/tolower/
568 [`strings.ToUpper`]: /functions/strings/toupper/
569 [`template`]: /functions/go-template/template/
570 [`text/template`]: https://pkg.go.dev/text/template
571 [`with`]: /functions/go-template/with/
572 [embedded templates]: /templates/embedded/
573 [front matter fields]: /content-management/front-matter/#fields
574 [front matter]: /content-management/front-matter/
575 [functions]: /functions/
576 [go-templates]: /functions/go-template/
577 [methods]: /methods/
578 [params_page]: /methods/page/params/
579 [params_site]: /methods/site/params/
580 [partial templates]: /templates/types/#partial
581 [templates]: /templates/