github.com/rabbouni145/gg@v0.47.1/docs/content/en/templates/introduction.md (about) 1 --- 2 title: Introduction to Hugo Templating 3 linktitle: Introduction 4 description: Hugo uses Go's `html/template` and `text/template` libraries as the basis for the templating. 5 godocref: https://golang.org/pkg/html/template/ 6 date: 2017-02-01 7 publishdate: 2017-02-01 8 lastmod: 2017-02-25 9 categories: [templates,fundamentals] 10 keywords: [go] 11 menu: 12 docs: 13 parent: "templates" 14 weight: 10 15 weight: 10 16 sections_weight: 10 17 draft: false 18 aliases: [/layouts/introduction/,/layout/introduction/, /templates/go-templates/] 19 toc: true 20 --- 21 22 {{% note %}} 23 The following is only a primer on Go templates. For an in-depth look into Go templates, check the official [Go docs](http://golang.org/pkg/html/template/). 24 {{% /note %}} 25 26 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. 27 28 {{< youtube gnJbPO-GFIw >}} 29 30 ## Basic Syntax 31 32 Go templates are HTML files with the addition of [variables][variables] and [functions][functions]. Go template variables and functions are accessible within `{{ }}`. 33 34 ### Access a Predefined Variable 35 36 ``` 37 {{ foo }} 38 ``` 39 40 Parameters for functions are separated using spaces. The following example calls the `add` function with inputs of `1` and `2`: 41 42 ``` 43 {{ add 1 2 }} 44 ``` 45 46 #### Methods and Fields are Accessed via dot Notation 47 48 Accessing the Page Parameter `bar` defined in a piece of content's [front matter][]. 49 50 ``` 51 {{ .Params.bar }} 52 ``` 53 54 #### Parentheses Can be Used to Group Items Together 55 56 ``` 57 {{ if or (isset .Params "alt") (isset .Params "caption") }} Caption {{ end }} 58 ``` 59 60 ## Variables 61 62 Each Go template gets a data object. In Hugo, each template is passed a `Page`. See [variables][] for more information. 63 64 This is how you access a `Page` variable from a template: 65 66 ``` 67 <title>{{ .Title }}</title> 68 ``` 69 70 Values can also be stored in custom variables and referenced later: 71 72 ``` 73 {{ $address := "123 Main St."}} 74 {{ $address }} 75 ``` 76 77 {{% warning %}} 78 Variables defined inside `if` conditionals and similar are not visible on the outside. See [https://github.com/golang/go/issues/10608](https://github.com/golang/go/issues/10608). 79 80 Hugo has created a workaround for this issue in [Scratch](/functions/scratch). 81 82 {{% /warning %}} 83 84 ## Functions 85 86 Go templates only ship with a few basic functions but also provide a mechanism for applications to extend the original set. 87 88 [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. 89 90 ### Example 1: Adding Numbers 91 92 ``` 93 {{ add 1 2 }} 94 => 3 95 ``` 96 97 ### Example 2: Comparing Numbers 98 99 ``` 100 {{ lt 1 2 }} 101 => true (i.e., since 1 is less than 2) 102 ``` 103 104 Note that both examples make use of Go template's [math functions][]. 105 106 {{% note "Additional Boolean Operators" %}} 107 There are more boolean operators than those listed in the Hugo docs in the [Go template documentation](http://golang.org/pkg/text/template/#hdr-Functions). 108 {{% /note %}} 109 110 ## Includes 111 112 When including another template, you will need to pass it the data that it would 113 need to access. 114 115 {{% note %}} 116 To pass along the current context, please remember to include a trailing **dot**. 117 {{% /note %}} 118 119 The templates location will always be starting at the `layouts/` directory 120 within Hugo. 121 122 ### Partial 123 124 The [`partial`][partials] function is used to include *partial* templates using 125 the syntax `{{ partial "<PATH>/<PARTIAL>.<EXTENSION>" . }}`. 126 127 Example: 128 129 ``` 130 {{ partial "header.html" . }} 131 ``` 132 133 ### Template 134 135 The `template` function was used to include *partial* templates in much older 136 Hugo versions. Now it is still useful for calling [*internal* 137 templates][internal_templates]: 138 139 ``` 140 {{ template "_internal/opengraph.html" . }} 141 ``` 142 143 ## Logic 144 145 Go templates provide the most basic iteration and conditional logic. 146 147 ### Iteration 148 149 Just like in Go, the Go templates make heavy use of `range` to iterate over 150 a map, array, or slice. The following are different examples of how to use 151 range. 152 153 #### Example 1: Using Context 154 155 ``` 156 {{ range array }} 157 {{ . }} 158 {{ end }} 159 ``` 160 161 #### Example 2: Declaring Value => Variable name 162 163 ``` 164 {{range $element := array}} 165 {{ $element }} 166 {{ end }} 167 ``` 168 169 #### Example 3: Declaring Key-Value Variable Name 170 171 ``` 172 {{range $index, $element := array}} 173 {{ $index }} 174 {{ $element }} 175 {{ end }} 176 ``` 177 178 ### Conditionals 179 180 `if`, `else`, `with`, `or`, and `and` provide the framework for handling conditional logic in Go Templates. Like `range`, each statement is closed with an `{{end}}`. 181 182 Go Templates treat the following values as false: 183 184 * false 185 * 0 186 * any zero-length array, slice, map, or string 187 188 #### Example 1: `if` 189 190 ``` 191 {{ if isset .Params "title" }}<h4>{{ index .Params "title" }}</h4>{{ end }} 192 ``` 193 194 #### Example 2: `if` … `else` 195 196 ``` 197 {{ if isset .Params "alt" }} 198 {{ index .Params "alt" }} 199 {{else}} 200 {{ index .Params "caption" }} 201 {{ end }} 202 ``` 203 204 #### Example 3: `and` & `or` 205 206 ``` 207 {{ if and (or (isset .Params "title") (isset .Params "caption")) (isset .Params "attr")}} 208 ``` 209 210 #### Example 4: `with` 211 212 An alternative way of writing "`if`" and then referencing the same value 213 is to use "`with`" instead. `with` rebinds the context `.` within its scope 214 and skips the block if the variable is absent. 215 216 The first example above could be simplified as: 217 218 ``` 219 {{ with .Params.title }}<h4>{{ . }}</h4>{{ end }} 220 ``` 221 222 #### Example 5: `if` … `else if` 223 224 ``` 225 {{ if isset .Params "alt" }} 226 {{ index .Params "alt" }} 227 {{ else if isset .Params "caption" }} 228 {{ index .Params "caption" }} 229 {{ end }} 230 ``` 231 232 ## Pipes 233 234 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. 235 236 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. 237 238 A few simple examples should help convey how to use the pipe. 239 240 ### Example 1: `shuffle` 241 242 The following two examples are functionally the same: 243 244 ``` 245 {{ shuffle (seq 1 5) }} 246 ``` 247 248 249 ``` 250 {{ (seq 1 5) | shuffle }} 251 ``` 252 253 ### Example 2: `index` 254 255 The following accesses the page parameter called "disqus_url" and escapes the HTML. This example also uses the [`index` function][index], which is built into Go templates: 256 257 ``` 258 {{ index .Params "disqus_url" | html }} 259 ``` 260 261 ### Example 3: `or` with `isset` 262 263 ``` 264 {{ if or (or (isset .Params "title") (isset .Params "caption")) (isset .Params "attr") }} 265 Stuff Here 266 {{ end }} 267 ``` 268 269 Could be rewritten as 270 271 ``` 272 {{ if isset .Params "caption" | or isset .Params "title" | or isset .Params "attr" }} 273 Stuff Here 274 {{ end }} 275 ``` 276 277 ### Example 4: Internet Explorer Conditional Comments {#ie-conditional-comments} 278 279 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: 280 281 ``` 282 {{ "<!--[if lt IE 9]>" | safeHTML }} 283 <script src="html5shiv.js"></script> 284 {{ "<![endif]-->" | safeHTML }} 285 ``` 286 287 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](http://golang.org/pkg/text/template/#hdr-Examples) in the Go text/template documentation: 288 289 ``` 290 {{ `<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7"><![endif]-->` | safeHTML }} 291 ``` 292 293 ## Context (aka "the dot") 294 295 The most easily overlooked concept to understand about Go templates is that `{{ . }}` always refers to the current context. In the top level of your template, this will be the data set made available to it. Inside of an iteration, however, it will have the value of the current item in the loop; i.e., `{{ . }}` will no longer refer to the data available to the entire page. If you need to access page-level data (e.g., page params set in front matter) from within the loop, you will likely want to do one of the following: 296 297 ### 1. Define a Variable Independent of Context 298 299 The following shows how to define a variable independent of the context. 300 301 {{< code file="tags-range-with-page-variable.html" >}} 302 {{ $title := .Site.Title }} 303 <ul> 304 {{ range .Params.tags }} 305 <li> 306 <a href="/tags/{{ . | urlize }}">{{ . }}</a> 307 - {{ $title }} 308 </li> 309 {{ end }} 310 </ul> 311 {{< /code >}} 312 313 {{% note %}} 314 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. 315 {{% /note %}} 316 317 ### 2. Use `$.` to Access the Global Context 318 319 `$` 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: 320 321 {{< code file="range-through-tags-w-global.html" >}} 322 <ul> 323 {{ range .Params.tags }} 324 <li> 325 <a href="/tags/{{ . | urlize }}">{{ . }}</a> 326 - {{ $.Site.Title }} 327 </li> 328 {{ end }} 329 </ul> 330 {{< /code >}} 331 332 {{% warning "Don't Redefine the Dot" %}} 333 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. 334 {{% /warning %}} 335 336 ## Whitespace 337 338 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. 339 340 For instance, the following Go template will include the newlines and horizontal tab in its HTML output: 341 342 ``` 343 <div> 344 {{ .Title }} 345 </div> 346 ``` 347 348 Which will output: 349 350 ``` 351 <div> 352 Hello, World! 353 </div> 354 ``` 355 356 Leveraging the `-` in the following example will remove the extra white space surrounding the `.Title` variable and remove the newline: 357 358 ``` 359 <div> 360 {{- .Title -}} 361 </div> 362 ``` 363 364 Which then outputs: 365 366 ``` 367 <div>Hello, World!</div> 368 ``` 369 370 Go considers the following characters whitespace: 371 372 * <kbd>space</kbd> 373 * horizontal <kbd>tab</kbd> 374 * carriage <kbd>return</kbd> 375 * newline 376 377 ## Comments 378 379 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. 380 381 ### Go templates comments 382 383 Go templates support `{{/*` and `*/}}` to open and close a comment block. Nothing within that block will be rendered. 384 385 For example: 386 387 ``` 388 Bonsoir, {{/* {{ add 0 + 2 }} */}}Eliott. 389 ``` 390 391 Will render `Bonsoir, Eliott.`, and not care about the syntax error (`add 0 + 2`) in the comment block. 392 393 ### HTML comments 394 395 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: 396 397 ``` 398 {{ printf "<!-- Our website is named: %s -->" .Site.Title | safeHTML }} 399 ``` 400 401 #### HTML comments containing Go templates 402 403 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. 404 405 {{% note %}} 406 Do **not** try to comment out Go template code using HTML comments. 407 {{% /note %}} 408 409 ``` 410 <!-- {{ $author := "Emma Goldman" }} was a great woman. --> 411 {{ $author }} 412 ``` 413 414 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. 415 416 ## Hugo Parameters 417 418 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 specified via `metaDataFormat` in your configuration file. 419 420 ## Use Content (`Page`) Parameters 421 422 You can provide variables to be used by templates in individual content's [front matter][]. 423 424 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`. 425 426 Here is the example front matter: 427 428 ``` 429 --- 430 title: Roadmap 431 lastmod: 2017-03-05 432 date: 2013-11-18 433 notoc: true 434 --- 435 ``` 436 437 Here is an example of corresponding code that could be used inside a `toc.html` [partial template][partials]: 438 439 {{< code file="layouts/partials/toc.html" download="toc.html" >}} 440 {{ if not .Params.notoc }} 441 <aside> 442 <header> 443 <a href="#{{.Title | urlize}}"> 444 <h3>{{.Title}}</h3> 445 </a> 446 </header> 447 {{.TableOfContents}} 448 </aside> 449 <a href="#" id="toc-toggle"></a> 450 {{end}} 451 {{< /code >}} 452 453 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`. 454 455 ## Use Site Configuration Parameters 456 457 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. 458 459 For instance, you might declare the following: 460 461 {{< code-toggle file="config" >}} 462 params: 463 copyrighthtml: "Copyright © 2017 John Doe. All Rights Reserved." 464 twitteruser: "spf13" 465 sidebarrecentlimit: 5 466 {{< /code >}} 467 468 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. 469 470 ``` 471 {{if .Site.Params.copyrighthtml}}<footer> 472 <div class="text-center">{{.Site.Params.CopyrightHTML | safeHTML}}</div> 473 </footer>{{end}} 474 ``` 475 476 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: 477 478 {{< code file="layouts/partials/twitter.html" >}} 479 {{with .Site.Params.twitteruser}} 480 <div> 481 <a href="https://twitter.com/{{.}}" rel="author"> 482 <img src="/images/twitter.png" width="48" height="48" title="Twitter: {{.}}" alt="Twitter"></a> 483 </div> 484 {{end}} 485 {{< /code >}} 486 487 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. 488 489 ``` 490 <nav> 491 <h1>Recent Posts</h1> 492 <ul> 493 {{- range first .Site.Params.SidebarRecentLimit .Site.Pages -}} 494 <li><a href="{{.RelPermalink}}">{{.Title}}</a></li> 495 {{- end -}} 496 </ul> 497 </nav> 498 ``` 499 500 ## Example: Show Only Upcoming Events 501 502 Go allows you to do more than what's shown here. Using Hugo's [`where` function][where] and Go built-ins, we can list only the items from `content/events/` whose date (set in a content file's [front matter][]) is in the future. The following is an example [partial template][partials]: 503 504 {{< code file="layouts/partials/upcoming-events.html" download="upcoming-events.html" >}} 505 <h4>Upcoming Events</h4> 506 <ul class="upcoming-events"> 507 {{ range where .Pages.ByDate "Section" "events" }} 508 {{ if ge .Date.Unix .Now.Unix }} 509 <li> 510 <!-- add span for event type --> 511 <span>{{ .Type | title }} —</span> 512 {{ .Title }} on 513 <!-- add span for event date --> 514 <span>{{ .Date.Format "2 January at 3:04pm" }}</span> 515 at {{ .Params.place }} 516 </li> 517 {{ end }} 518 {{ end }} 519 </ul> 520 {{< /code >}} 521 522 523 [`where` function]: /functions/where/ 524 [config]: /getting-started/configuration/ 525 [dotdoc]: http://golang.org/pkg/text/template/#hdr-Variables 526 [first]: /functions/first/ 527 [front matter]: /content-management/front-matter/ 528 [functions]: /functions/ "See the full list of Hugo's templating functions with a quick start reference guide and basic and advanced examples." 529 [Go html/template]: http://golang.org/pkg/html/template/ "Godocs references for Go's html templating" 530 [gohtmltemplate]: http://golang.org/pkg/html/template/ "Godocs references for Go's html templating" 531 [index]: /functions/index/ 532 [math functions]: /functions/math/ 533 [partials]: /templates/partials/ "Link to the partial templates page inside of the templating section of the Hugo docs" 534 [internal_templates]: /templates/internal/ 535 [relpermalink]: /variables/page/ 536 [safehtml]: /functions/safehtml/ 537 [sitevars]: /variables/site/ 538 [variables]: /variables/ "See the full extent of page-, site-, and other variables that Hugo make available to you in your templates." 539 [where]: /functions/where/ 540 [with]: /functions/with/ 541 [godocsindex]: http://golang.org/pkg/text/template/ "Godocs page for index function"