default.md (2465B)
1 ---
2 title: default
3 description: Allows setting a default value that can be returned if a first value is not set.
4 qref: "Returns a default value if a value is not set when checked."
5 date: 2017-02-01
6 publishdate: 2017-02-01
7 lastmod: 2017-02-01
8 keywords: [defaults]
9 categories: [functions]
10 menu:
11 docs:
12 parent: "functions"
13 toc:
14 signature: ["default DEFAULT INPUT"]
15 workson: []
16 hugoversion:
17 relatedfuncs: []
18 deprecated: false
19 draft: false
20 aliases: []
21 ---
22
23 `default` checks whether a given value is set and returns a default value if it is not. *Set* in this context means different things depending on the data type:
24
25 * non-zero for numeric types and times
26 * non-zero length for strings, arrays, slices, and maps
27 * any boolean or struct value
28 * non-nil for any other types
29
30 `default` function examples reference the following content page:
31
32 {{< code file="content/posts/default-function-example.md" >}}
33 ---
34 title: Sane Defaults
35 seo_title:
36 date: 2017-02-18
37 font:
38 oldparam: The default function helps make your templating DRYer.
39 newparam:
40 ---
41 {{< /code >}}
42
43 `default` can be written in more than one way:
44
45 ```
46 {{ index .Params "font" | default "Roboto" }}
47 {{ default "Roboto" (index .Params "font") }}
48 ```
49
50 Both of the above `default` function calls return `Roboto`.
51
52 A `default` value, however, does not need to be hard coded like the previous example. The `default` value can be a variable or pulled directly from the front matter using dot notation:
53
54 {{< code file="variable-as-default-value.html" nocopy="true" >}}
55 {{$old := .Params.oldparam }}
56 <p>{{ .Params.newparam | default $old }}</p>
57 {{< /code >}}
58
59 Which would return:
60
61 ```
62 <p>The default function helps make your templating DRYer.</p>
63 ```
64
65 And then using dot notation
66
67 {{< code file="dot-notation-default-value.html" >}}
68 <title>{{ .Params.seo_title | default .Title }}</title>
69 {{< /code >}}
70
71 Which would return
72
73 {{< output file="dot-notation-default-return-value.html" >}}
74 <title>Sane Defaults</title>
75 {{< /output >}}
76
77 The following have equivalent return values but are far less terse. This demonstrates the utility of `default`:
78
79 Using `if`:
80
81 {{< code file="if-instead-of-default.html" nocopy="true" >}}
82 <title>{{if .Params.seo_title}}{{.Params.seo_title}}{{else}}{{.Title}}{{end}}</title>
83 => Sane Defaults
84 {{< /code >}}
85
86 Using `with`:
87
88 {{< code file="with-instead-of-default.html" nocopy="true" >}}
89 <title>{{with .Params.seo_title}}{{.}}{{else}}{{.Title}}{{end}}</title>
90 => Sane Defaults
91 {{< /code >}}