introduction.md (21361B)
1 ---
2 title: Introduction to Hugo Templating
3 linktitle: Templating
4 description: Hugo uses Go's `html/template` and `text/template` libraries as the basis for the templating.
5 date: 2017-02-01
6 publishdate: 2017-02-01
7 lastmod: 2017-02-25
8 categories: [templates,fundamentals]
9 keywords: [go]
10 menu:
11 docs:
12 parent: "templates"
13 weight: 10
14 weight: 10
15 sections_weight: 10
16 draft: false
17 aliases: [/layouts/introduction/,/layout/introduction/, /templates/go-templates/]
18 toc: true
19 ---
20
21 {{% note %}}
22 The following is only a primer on Go Templates. For an in-depth look into Go Templates, check the official [Go docs](https://golang.org/pkg/text/template/).
23 {{% /note %}}
24
25 Go Templates provide an extremely simple template language that adheres to the belief that only the most basic of logic belongs in the template or view layer.
26
27 ## Basic Syntax
28
29 Go Templates are HTML files with the addition of [variables][variables] and [functions][functions]. Go Template variables and functions are accessible within `{{ }}`.
30
31 ### Access a Predefined Variable
32
33 A _predefined variable_ could be a variable already existing in the
34 current scope (like the `.Title` example in the [Variables]({{< relref
35 "#variables" >}}) section below) or a custom variable (like the
36 `$address` example in that same section).
37
38
39 ```go-html-template
40 {{ .Title }}
41 {{ $address }}
42 ```
43
44 Parameters for functions are separated using spaces. The general syntax is:
45
46 ```
47 {{ FUNCTION ARG1 ARG2 .. }}
48 ```
49
50 The following example calls the `add` function with inputs of `1` and `2`:
51
52 ```go-html-template
53 {{ add 1 2 }}
54 ```
55
56 #### Methods and Fields are Accessed via dot Notation
57
58 Accessing the Page Parameter `bar` defined in a piece of content's [front matter][].
59
60 ```go-html-template
61 {{ .Params.bar }}
62 ```
63
64 #### Parentheses Can be Used to Group Items Together
65
66 ```go-html-template
67 {{ if or (isset .Params "alt") (isset .Params "caption") }} Caption {{ end }}
68 ```
69
70 #### A Single Statement Can be Split over Multiple Lines
71
72 ```go-html-template
73 {{ if or
74 (isset .Params "alt")
75 (isset .Params "caption")
76 }}
77 ```
78
79 #### Raw String Literals Can Include Newlines
80
81 ```go-html-template
82 {{ $msg := `Line one.
83 Line two.` }}
84 ```
85
86 ## Variables {#variables}
87
88 Each Go Template gets a data object. In Hugo, each template is passed
89 a `Page`. In the below example, `.Title` is one of the elements
90 accessible in that [`Page` variable][pagevars].
91
92 With the `Page` being the default scope of a template, the `Title`
93 element in current scope (`.` -- "the **dot**") is accessible simply
94 by the dot-prefix (`.Title`):
95
96 ```go-html-template
97 <title>{{ .Title }}</title>
98 ```
99
100 Values can also be stored in custom variables and referenced later:
101
102 {{% note %}}
103 The custom variables need to be prefixed with `$`.
104 {{% /note %}}
105
106 ```go-html-template
107 {{ $address := "123 Main St." }}
108 {{ $address }}
109 ```
110 Variables can be re-defined using the `=` operator. The example below
111 prints "Var is Hugo Home" on the home page, and "Var is Hugo Page" on
112 all other pages:
113
114 ```go-html-template
115 {{ $var := "Hugo Page" }}
116 {{ if .IsHome }}
117 {{ $var = "Hugo Home" }}
118 {{ end }}
119 Var is {{ $var }}
120 ```
121
122 ## Functions
123
124 Go Templates only ship with a few basic functions but also provide a mechanism for applications to extend the original set.
125
126 [Hugo template functions][functions] provide additional functionality specific to building websites. Functions are called by using their name followed by the required parameters separated by spaces. Template functions cannot be added without recompiling Hugo.
127
128 ### Example 1: Adding Numbers
129
130 ```go-html-template
131 {{ add 1 2 }}
132 <!-- prints 3 -->
133 ```
134
135 ### Example 2: Comparing Numbers
136
137 ```go-html-template
138 {{ lt 1 2 }}
139 <!-- prints true (i.e., since 1 is less than 2) -->
140 ```
141
142 Note that both examples make use of Go Template's [math]][] functions.
143
144 {{% note "Additional Boolean Operators" %}}
145 There are more boolean operators than those listed in the Hugo docs in the [Go Template documentation](https://golang.org/pkg/text/template/#hdr-Functions).
146 {{% /note %}}
147
148 ## Includes
149
150 When including another template, you will need to pass it the data that it would
151 need to access.
152
153 {{% note %}}
154 To pass along the current context, please remember to include a trailing **dot**.
155 {{% /note %}}
156
157 The templates location will always be starting at the `layouts/` directory
158 within Hugo.
159
160 ### Partial
161
162 The [`partial`][partials] function is used to include *partial* templates using
163 the syntax `{{ partial "<PATH>/<PARTIAL>.<EXTENSION>" . }}`.
164
165 Example of including a `layouts/partials/header.html` partial:
166
167 ```go-html-template
168 {{ partial "header.html" . }}
169 ```
170
171 ### Template
172
173 The `template` function was used to include *partial* templates
174 in much older Hugo versions. Now it's useful only for calling
175 [*internal* templates][internal templates]. The syntax is `{{ template
176 "_internal/<TEMPLATE>.<EXTENSION>" . }}`.
177
178 {{% note %}}
179 The available **internal** templates can be found
180 [here](https://github.com/gohugoio/hugo/tree/master/tpl/tplimpl/embedded/templates).
181 {{% /note %}}
182
183 Example of including the internal `opengraph.html` template:
184
185 ```go-html-template
186 {{ template "_internal/opengraph.html" . }}
187 ```
188
189 ## Logic
190
191 Go Templates provide the most basic iteration and conditional logic.
192
193 ### Iteration
194
195 The Go Templates make heavy use of `range` to iterate over a _map_,
196 _array_, or _slice_. The following are different examples of how to
197 use `range`.
198
199 #### Example 1: Using Context (`.`)
200
201 ```go-html-template
202 {{ range $array }}
203 {{ . }} <!-- The . represents an element in $array -->
204 {{ end }}
205 ```
206
207 #### Example 2: Declaring a variable name for an array element's value
208
209 ```go-html-template
210 {{ range $elem_val := $array }}
211 {{ $elem_val }}
212 {{ end }}
213 ```
214
215 #### Example 3: Declaring variable names for an array element's index _and_ value
216
217 For an array or slice, the first declared variable will map to each
218 element's index.
219
220 ```go-html-template
221 {{ range $elem_index, $elem_val := $array }}
222 {{ $elem_index }} -- {{ $elem_val }}
223 {{ end }}
224 ```
225
226 #### Example 4: Declaring variable names for a map element's key _and_ value
227
228 For a map, the first declared variable will map to each map element's
229 key.
230
231 ```go-html-template
232 {{ range $elem_key, $elem_val := $map }}
233 {{ $elem_key }} -- {{ $elem_val }}
234 {{ end }}
235 ```
236
237 #### Example 5: Conditional on empty _map_, _array_, or _slice_.
238
239 If the _map_, _array_, or _slice_ passed into the range is zero-length then the else statement is evaluated.
240
241 ```go-html-template
242 {{ range $array }}
243 {{ . }}
244 {{else}}
245 <!-- This is only evaluated if $array is empty -->
246 {{ end }}
247 ```
248
249 ### Conditionals
250
251 `if`, `else`, `with`, `or`, `and` and `not` provide the framework for handling conditional logic in Go Templates. Like `range`, `if` and `with` statements are closed with an `{{ end }}`.
252
253 Go Templates treat the following values as **false**:
254
255 - `false` (boolean)
256 - 0 (integer)
257 - any zero-length array, slice, map, or string
258
259 #### Example 1: `with`
260
261 It is common to write "if something exists, do this" kind of
262 statements using `with`.
263
264 {{% note %}}
265 `with` rebinds the context `.` within its scope (just like in `range`).
266 {{% /note %}}
267
268 It skips the block if the variable is absent, or if it evaluates to
269 "false" as explained above.
270
271 ```go-html-template
272 {{ with .Params.title }}
273 <h4>{{ . }}</h4>
274 {{ end }}
275 ```
276
277 #### Example 2: `with` .. `else`
278
279 Below snippet uses the "description" front-matter parameter's value if
280 set, else uses the default `.Summary` [Page variable][pagevars]:
281
282
283 ```go-html-template
284 {{ with .Param "description" }}
285 {{ . }}
286 {{ else }}
287 {{ .Summary }}
288 {{ end }}
289 ```
290
291 See the [`.Param` function][param].
292
293 #### Example 3: `if`
294
295 An alternative (and a more verbose) way of writing `with` is using
296 `if`. Here, the `.` does not get rebinded.
297
298 Below example is "Example 1" rewritten using `if`:
299
300 ```go-html-template
301 {{ if isset .Params "title" }}
302 <h4>{{ index .Params "title" }}</h4>
303 {{ end }}
304 ```
305
306 #### Example 4: `if` .. `else`
307
308 Below example is "Example 2" rewritten using `if` .. `else`, and using
309 [`isset` function][isset] + `.Params` variable (different from the
310 [`.Param` **function**][param]) instead:
311
312 ```go-html-template
313 {{ if (isset .Params "description") }}
314 {{ index .Params "description" }}
315 {{ else }}
316 {{ .Summary }}
317 {{ end }}
318 ```
319
320 #### Example 5: `if` .. `else if` .. `else`
321
322 Unlike `with`, `if` can contain `else if` clauses too.
323
324 ```go-html-template
325 {{ if (isset .Params "description") }}
326 {{ index .Params "description" }}
327 {{ else if (isset .Params "summary") }}
328 {{ index .Params "summary" }}
329 {{ else }}
330 {{ .Summary }}
331 {{ end }}
332 ```
333
334 #### Example 6: `and` & `or`
335
336 ```go-html-template
337 {{ if (and (or (isset .Params "title") (isset .Params "caption")) (isset .Params "attr")) }}
338 ```
339
340 ## Pipes
341
342 One of the most powerful components of Go Templates is the ability to stack actions one after another. This is done by using pipes. Borrowed from Unix pipes, the concept is simple: each pipeline's output becomes the input of the following pipe.
343
344 Because of the very simple syntax of Go Templates, the pipe is essential to being able to chain together function calls. One limitation of the pipes is that they can only work with a single value and that value becomes the last parameter of the next pipeline.
345
346 A few simple examples should help convey how to use the pipe.
347
348 ### Example 1: `shuffle`
349
350 The following two examples are functionally the same:
351
352 ```go-html-template
353 {{ shuffle (seq 1 5) }}
354 ```
355
356
357 ```go-html-template
358 {{ (seq 1 5) | shuffle }}
359 ```
360
361 ### Example 2: `index`
362
363 The following accesses the page parameter called "disqus_url" and escapes the HTML. This example also uses the [`index` function](/functions/index-function/), which is built into Go Templates:
364
365 ```go-html-template
366 {{ index .Params "disqus_url" | html }}
367 ```
368
369 ### Example 3: `or` with `isset`
370
371 ```go-html-template
372 {{ if or (or (isset .Params "title") (isset .Params "caption")) (isset .Params "attr") }}
373 Stuff Here
374 {{ end }}
375 ```
376
377 Could be rewritten as
378
379 ```go-html-template
380 {{ if isset .Params "caption" | or isset .Params "title" | or isset .Params "attr" }}
381 Stuff Here
382 {{ end }}
383 ```
384
385 ### Example 4: Internet Explorer Conditional Comments {#ie-conditional-comments}
386
387 By default, Go Templates remove HTML comments from output. This has the unfortunate side effect of removing Internet Explorer conditional comments. As a workaround, use something like this:
388
389 ```go-html-template
390 {{ "<!--[if lt IE 9]>" | safeHTML }}
391 <script src="html5shiv.js"></script>
392 {{ "<![endif]-->" | safeHTML }}
393 ```
394
395 Alternatively, you can use the backtick (`` ` ``) to quote the IE conditional comments, avoiding the tedious task of escaping every double quotes (`"`) inside, as demonstrated in the [examples](https://golang.org/pkg/text/template/#hdr-Examples) in the Go text/template documentation:
396
397 ```go-html-template
398 {{ `<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7"><![endif]-->` | safeHTML }}
399 ```
400
401 ## Context (aka "the dot") {#the-dot}
402
403 The most easily overlooked concept to understand about Go Templates is
404 that `{{ . }}` always refers to the **current context**.
405
406 - In the top level of your template, this will be the data set made
407 available to it.
408 - Inside of an iteration, however, it will have the value of the
409 current item in the loop; i.e., `{{ . }}` will no longer refer to
410 the data available to the entire page.
411
412 If you need to access page-level data (e.g., page params set in front
413 matter) from within the loop, you will likely want to do one of the
414 following:
415
416 ### 1. Define a Variable Independent of Context
417
418 The following shows how to define a variable independent of the context.
419
420 {{< code file="tags-range-with-page-variable.html" >}}
421 {{ $title := .Site.Title }}
422 <ul>
423 {{ range .Params.tags }}
424 <li>
425 <a href="/tags/{{ . | urlize }}">{{ . }}</a>
426 - {{ $title }}
427 </li>
428 {{ end }}
429 </ul>
430 {{< /code >}}
431
432 {{% note %}}
433 Notice how once we have entered the loop (i.e. `range`), the value of `{{ . }}` has changed. We have defined a variable outside of the loop (`{{$title}}`) that we've assigned a value so that we have access to the value from within the loop as well.
434 {{% /note %}}
435
436 ### 2. Use `$.` to Access the Global Context
437
438 `$` has special significance in your templates. `$` is set to the starting value of `.` ("the dot") by default. This is a [documented feature of Go text/template][dotdoc]. This means you have access to the global context from anywhere. Here is an equivalent example of the preceding code block but now using `$` to grab `.Site.Title` from the global context:
439
440 {{< code file="range-through-tags-w-global.html" >}}
441 <ul>
442 {{ range .Params.tags }}
443 <li>
444 <a href="/tags/{{ . | urlize }}">{{ . }}</a>
445 - {{ $.Site.Title }}
446 </li>
447 {{ end }}
448 </ul>
449 {{< /code >}}
450
451 {{% warning "Don't Redefine the Dot" %}}
452 The built-in magic of `$` would cease to work if someone were to mischievously redefine the special character; e.g. `{{ $ := .Site }}`. *Don't do it.* You may, of course, recover from this mischief by using `{{ $ := . }}` in a global context to reset `$` to its default value.
453 {{% /warning %}}
454
455 ## Whitespace
456
457 Go 1.6 includes the ability to trim the whitespace from either side of a Go tag by including a hyphen (`-`) and space immediately beside the corresponding `{{` or `}}` delimiter.
458
459 For instance, the following Go Template will include the newlines and horizontal tab in its HTML output:
460
461 ```go-html-template
462 <div>
463 {{ .Title }}
464 </div>
465 ```
466
467 Which will output:
468
469 ```html
470 <div>
471 Hello, World!
472 </div>
473 ```
474
475 Leveraging the `-` in the following example will remove the extra white space surrounding the `.Title` variable and remove the newline:
476
477 ```go-html-template
478 <div>
479 {{- .Title -}}
480 </div>
481 ```
482
483 Which then outputs:
484
485 ```html
486 <div>Hello, World!</div>
487 ```
488
489 Go considers the following characters _whitespace_:
490
491 * <kbd>space</kbd>
492 * horizontal <kbd>tab</kbd>
493 * carriage <kbd>return</kbd>
494 * newline
495
496 ## Comments
497
498 In order to keep your templates organized and share information throughout your team, you may want to add comments to your templates. There are two ways to do that with Hugo.
499
500 ### Go Templates comments
501
502 Go Templates support `{{/*` and `*/}}` to open and close a comment block. Nothing within that block will be rendered.
503
504 For example:
505
506 ```go-html-template
507 Bonsoir, {{/* {{ add 0 + 2 }} */}}Eliott.
508 ```
509
510 Will render `Bonsoir, Eliott.`, and not care about the syntax error (`add 0 + 2`) in the comment block.
511
512 ### HTML comments
513
514 If you need to produce HTML comments from your templates, take a look at the [Internet Explorer conditional comments](#ie-conditional-comments) example. If you need variables to construct such HTML comments, just pipe `printf` to `safeHTML`. For example:
515
516 ```go-html-template
517 {{ printf "<!-- Our website is named: %s -->" .Site.Title | safeHTML }}
518 ```
519
520 #### HTML comments containing Go Templates
521
522 HTML comments are by default stripped, but their content is still evaluated. That means that although the HTML comment will never render any content to the final HTML pages, code contained within the comment may fail the build process.
523
524 {{% note %}}
525 Do **not** try to comment out Go Template code using HTML comments.
526 {{% /note %}}
527
528 ```go-html-template
529 <!-- {{ $author := "Emma Goldman" }} was a great woman. -->
530 {{ $author }}
531 ```
532
533 The templating engine will strip the content within the HTML comment, but will first evaluate any Go Template code if present within. So the above example will render `Emma Goldman`, as the `$author` variable got evaluated in the HTML comment. But the build would have failed if that code in the HTML comment had an error.
534
535 ## Hugo Parameters
536
537 Hugo provides the option of passing values to your template layer through your [site configuration][config] (i.e. for site-wide values) or through the metadata of each specific piece of content (i.e. the [front matter][]). You can define any values of any type and use them however you want in your templates, as long as the values are supported by the [front matter format]({{< ref "front-matter.md#front-matter-formats" >}}).
538
539 ## Use Content (`Page`) Parameters
540
541 You can provide variables to be used by templates in individual content's [front matter][].
542
543 An example of this is used in the Hugo docs. Most of the pages benefit from having the table of contents provided, but sometimes the table of contents doesn't make a lot of sense. We've defined a `notoc` variable in our front matter that will prevent a table of contents from rendering when specifically set to `true`.
544
545 Here is the example front matter (YAML):
546
547 ```
548 ---
549 title: Roadmap
550 lastmod: 2017-03-05
551 date: 2013-11-18
552 notoc: true
553 ---
554 ```
555
556 Here is an example of corresponding code that could be used inside a `toc.html` [partial template][partials]:
557
558 {{< code file="layouts/partials/toc.html" download="toc.html" >}}
559 {{ if not .Params.notoc }}
560 <aside>
561 <header>
562 <a href="#{{.Title | urlize}}">
563 <h3>{{.Title}}</h3>
564 </a>
565 </header>
566 {{.TableOfContents}}
567 </aside>
568 <a href="#" id="toc-toggle"></a>
569 {{ end }}
570 {{< /code >}}
571
572 We want the *default* behavior to be for pages to include a TOC unless otherwise specified. This template checks to make sure that the `notoc:` field in this page's front matter is not `true`.
573
574 ## Use Site Configuration Parameters
575
576 You can arbitrarily define as many site-level parameters as you want in your [site's configuration file][config]. These parameters are globally available in your templates.
577
578 For instance, you might declare the following:
579
580 {{< code-toggle file="config" >}}
581 params:
582 copyrighthtml: "Copyright © 2017 John Doe. All Rights Reserved."
583 twitteruser: "spf13"
584 sidebarrecentlimit: 5
585 {{< /code >}}
586
587 Within a footer layout, you might then declare a `<footer>` that is only rendered if the `copyrighthtml` parameter is provided. If it *is* provided, you will then need to declare the string is safe to use via the [`safeHTML` function][safehtml] so that the HTML entity is not escaped again. This would let you easily update just your top-level config file each January 1st, instead of hunting through your templates.
588
589 ```go-html-template
590 {{ if .Site.Params.copyrighthtml }}
591 <footer>
592 <div class="text-center">{{.Site.Params.CopyrightHTML | safeHTML}}</div>
593 </footer>
594 {{ end }}
595 ```
596
597 An alternative way of writing the "`if`" and then referencing the same value is to use [`with`][with] instead. `with` rebinds the context (`.`) within its scope and skips the block if the variable is absent:
598
599 {{< code file="layouts/partials/twitter.html" >}}
600 {{ with .Site.Params.twitteruser }}
601 <div>
602 <a href="https://twitter.com/{{.}}" rel="author">
603 <img src="/images/twitter.png" width="48" height="48" title="Twitter: {{.}}" alt="Twitter"></a>
604 </div>
605 {{ end }}
606 {{< /code >}}
607
608 Finally, you can pull "magic constants" out of your layouts as well. The following uses the [`first`][first] function, as well as the [`.RelPermalink`][relpermalink] page variable and the [`.Site.Pages`][sitevars] site variable.
609
610 ```go-html-template
611 <nav>
612 <h1>Recent Posts</h1>
613 <ul>
614 {{- range first .Site.Params.SidebarRecentLimit .Site.Pages -}}
615 <li><a href="{{.RelPermalink}}">{{.Title}}</a></li>
616 {{- end -}}
617 </ul>
618 </nav>
619 ```
620
621 ## Example: Show Future Events
622
623 Given the following content structure and [front matter]:
624
625 ```text
626 content/
627 └── events/
628 ├── event-1.md
629 ├── event-2.md
630 └── event-3.md
631 ```
632
633 {{< code-toggle file="content/events/event-1.md" copy="false" >}}
634 title = 'Event 1'
635 date = 2021-12-06T10:37:16-08:00
636 draft = false
637 start_date = 2021-12-05T09:00:00-08:00
638 end_date = 2021-12-05T11:00:00-08:00
639 {{< /code-toggle >}}
640
641 This [partial template][partials] renders future events:
642
643 {{< code file="layouts/partials/future-events.html" >}}
644 <h2>Future Events</h2>
645 <ul>
646 {{ range where site.RegularPages "Type" "events" }}
647 {{ if gt (.Params.start_date | time.AsTime) now }}
648 {{ $startDate := .Params.start_date | time.Format ":date_medium" }}
649 <li>
650 <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a> - {{ $startDate }}
651 </li>
652 {{ end }}
653 {{ end }}
654 </ul>
655 {{< /code >}}
656
657 If you restrict front matter to the TOML format, and omit quotation marks surrounding date fields, you can perform date comparisons without casting.
658
659 {{< code file="layouts/partials/future-events.html" >}}
660 <h2>Future Events</h2>
661 <ul>
662 {{ range where (where site.RegularPages "Type" "events") "Params.start_date" "gt" now }}
663 {{ $startDate := .Params.start_date | time.Format ":date_medium" }}
664 <li>
665 <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a> - {{ $startDate }}
666 </li>
667 {{ end }}
668 </ul>
669 {{< /code >}}
670
671 [config]: {{< relref "getting-started/configuration" >}}
672 [dotdoc]: https://golang.org/pkg/text/template/#hdr-Variables
673 [first]: {{< relref "functions/first" >}}
674 [front matter]: {{< relref "content-management/front-matter" >}}
675 [functions]: {{< relref "functions" >}}
676 [internal templates]: {{< relref "templates/internal" >}}
677 [isset]: {{< relref "functions/isset" >}}
678 [math]: {{< relref "functions/math" >}}
679 [pagevars]: {{< relref "variables/page" >}}
680 [param]: {{< relref "functions/param" >}}
681 [partials]: {{< relref "templates/partials" >}}
682 [relpermalink]: {{< relref "variables/page#page-variables" >}}
683 [safehtml]: {{< relref "functions/safehtml" >}}
684 [sitevars]: {{< relref "variables/site" >}}
685 [variables]: {{< relref "variables" >}}
686 [with]: {{< relref "functions/with" >}}