| 1 |
--- |
| 2 |
title: partials.Include |
| 3 |
description: Executes the given template, optionally passing context. If the partial template contains a return statement, returns the given value, else returns the rendered output. |
| 4 |
categories: [] |
| 5 |
keywords: [] |
| 6 |
params: |
| 7 |
functions_and_methods: |
| 8 |
aliases: [partial] |
| 9 |
returnType: any |
| 10 |
signatures: ['partials.Include NAME [CONTEXT]'] |
| 11 |
aliases: [/functions/partial] |
| 12 |
--- |
| 13 |
|
| 14 |
Without a [`return`][] statement, the `partial` function returns a string of type `template.HTML`. With a `return` statement, the `partial` function can return any data type. |
| 15 |
|
| 16 |
In this example we have three _partial_ templates: |
| 17 |
|
| 18 |
```tree |
| 19 |
layouts/ |
| 20 |
└── _partials/ |
| 21 |
├── average.html |
| 22 |
├── breadcrumbs.html |
| 23 |
└── footer.html |
| 24 |
``` |
| 25 |
|
| 26 |
The "average" partial returns the average of one or more numbers. We pass the numbers in context: |
| 27 |
|
| 28 |
```go-html-template |
| 29 |
{{ $numbers := slice 1 6 7 42 }} |
| 30 |
{{ $average := partial "average.html" $numbers }} |
| 31 |
``` |
| 32 |
|
| 33 |
The "breadcrumbs" partial renders [breadcrumb navigation][], and needs to receive the current page in context: |
| 34 |
|
| 35 |
```go-html-template |
| 36 |
{{ partial "breadcrumbs.html" . }} |
| 37 |
``` |
| 38 |
|
| 39 |
The "footer" partial renders the site footer. In this contrived example, the footer does not need access to the current page, so we can omit context: |
| 40 |
|
| 41 |
```go-html-template |
| 42 |
{{ partial "footer.html" }} |
| 43 |
``` |
| 44 |
|
| 45 |
You can pass anything in context: a page, a page collection, a scalar value, a slice, or a map. In this example we pass the current page and three scalar values: |
| 46 |
|
| 47 |
```go-html-template |
| 48 |
{{ $ctx := dict |
| 49 |
"page" . |
| 50 |
"name" "John Doe" |
| 51 |
"major" "Finance" |
| 52 |
"gpa" 4.0 |
| 53 |
}} |
| 54 |
{{ partial "render-student-info.html" $ctx }} |
| 55 |
``` |
| 56 |
|
| 57 |
Then, within the _partial_ template: |
| 58 |
|
| 59 |
```go-html-template |
| 60 |
<p>{{ .name }} is majoring in {{ .major }}.</p> |
| 61 |
<p>Their grade point average is {{ .gpa }}.</p> |
| 62 |
<p>See <a href="{{ .page.RelPermalink }}">details.</a></p> |
| 63 |
``` |
| 64 |
|
| 65 |
To return a value from a _partial_ template, it must contain only one `return` statement, placed at the end of the template: |
| 66 |
|
| 67 |
```go-html-template |
| 68 |
{{ $result := "" }} |
| 69 |
{{ if math.ModBool . 2 }} |
| 70 |
{{ $result = "even" }} |
| 71 |
{{ else }} |
| 72 |
{{ $result = "odd" }} |
| 73 |
{{ end }} |
| 74 |
{{ return $result }} |
| 75 |
``` |
| 76 |
|
| 77 |
[`return`]: /functions/go-template/return/ |
| 78 |
[breadcrumb navigation]: /content-management/sections/#ancestors-and-descendants |