Merge commit 'ec4e6f9df2' as 'docs'

This commit is contained in:
Bjørn Erik Pedersen 2017-08-10 17:18:22 +02:00
commit a1900826b9
839 changed files with 44703 additions and 0 deletions

View file

@ -0,0 +1,65 @@
---
title: .GetPage
description: "Gets a `Page` of a given `Kind` and `path`."
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [sections,lists,indexes]
signature: [".GetPage TYPE PATH"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
Every `Page` has a `Kind` attribute that shows what kind of page it is. While this attribute can be used to list pages of a certain `kind` using `where`, often it can be useful to fetch a single page by its path.
`.GetPage` looks up a page of a given `Kind` and `path`.
```
{{ with .Site.GetPage "section" "blog" }}{{ .Title }}{{ end }}
```
This method wil return `nil` when no page could be found, so the above will not print anything if the blog section isn't found.
For a regular page:
```
{{ with .Site.GetPage "page" "blog" "my-post.md" }}{{ .Title }}{{ end }}
```
Note that the path can also be supplied like this:
```
{{ with .Site.GetPage "page" "blog/my-post.md" }}{{ .Title }}{{ end }}
```
The valid page kinds are: *page, home, section, taxonomy and taxonomyTerm.*
## `.GetPage` Example
This code snippet---in the form of a [partial template][partials]---allows you to do the following:
1. Grab the index object of your `tags` [taxonomy][].
2. Assign this object to a variable, `$t`
3. Sort the terms associated with the taxonomy by popularity.
4. Grab the top two most popular terms in the taxonomy (i.e., the two most popular tags assigned to content.
{{< code file="grab-top-two-tags.html" >}}
<ul class="most-popular-tags">
{{ $t := $.Site.GetPage "taxonomyTerm" "tags" }}
{{ range first 2 $t.Data.Terms.ByCount }}
<li>{{.}}</li>
{{ end }}
</ul>
{{< /code >}}
[partials]: /templates/partials/
[taxonomy]: /content-management/taxonomies/

View file

@ -0,0 +1,34 @@
---
title: lang.NumFmt
description: "Formats a number with a given precision using the requested `decimal`, `grouping`, and `negative` characters."
godocref: ""
workson: []
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
#tags: [numbers]
menu:
docs:
parent: "functions"
toc: false
signature: ["lang.NumFmt <decimal> <grouping> <negative> <precision> <number>"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
draft: false
aliases: []
comments:
---
The default options value is `- . ,`.
Numbers greater than or equal to 5 are rounded up. For example, if precision is set to `0`, `1.5` becomes `2`, and `1.4` becomes `1`.
```
{{ lang.NumFmt "," "." "-" 2 12345.6789 }} → 12.345,68
{{ lang.NumFmt "." "" "-" 6 -12345.6789 }} → -12345.678900
{{ lang.NumFmt "." "," "-" 0 -12345.6789 }} → -12,346
{{ -98765.4321 | lang.NumFmt "." "," "-" 2 }} → -98,765.43
```

View file

@ -0,0 +1,20 @@
---
title: Functions Quick Reference
linktitle: Functions Quick Reference
description: Comprehensive list of Hugo templating functions, including basic and advanced usage examples.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
#tags: []
menu:
docs:
parent: "functions"
weight: 01 #rem
draft: false
aliases: [/layout/functions/,/templates/functions]
---
Go templates are lightweight but extensible. Go itself supplies built-in functions, including comparison operators and other basic tools. These are listed in the [Go template documentation][gofuncs]. Hugo has added additional functions to the basic template logic.
[gofuncs]: http://golang.org/pkg/text/template/#hdr-Functions

View file

@ -0,0 +1,28 @@
---
title: absLangURL
description: Adds the absolute URL with correct language prefix according to site configuration for multilingual.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [multilingual,i18n,urls]
signature: ["absLangURL INPUT"]
workson: []
hugoversion:
relatedfuncs: [relLangURL]
deprecated: false
aliases: []
---
Both `absLangURL` and [`relLangURL`](/functions/rellangurl/) are similar to their [`absURL`](/functions/absurl/) and [`relURL`](/functions/relurl) relatives but will add the correct language prefix when the site is configured with more than one language.
So for a site `baseURL` set to `https://example.com/hugo/` and the current language is `en`:
```
{{ "blog/" | absLangURL }} → "https://example.com/hugo/en/blog/"
{{ "blog/" | relLangURL }} → "/hugo/en/blog/"
```

View file

@ -0,0 +1,51 @@
---
title: absURL
description: Creates an absolute URL based on the configured baseURL.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [urls]
signature: ["absURL INPUT"]
workson: []
hugoversion:
relatedfuncs: [relURL]
deprecated: false
aliases: []
---
Both `absURL` and `relURL` consider the configured value of `baseURL` in your site's [`config` file][configuration]. Given a `baseURL` set to `https://example.com/hugo/`:
```
{{ "mystyle.css" | absURL }} → "https://example.com/hugo/mystyle.css"
{{ "mystyle.css" | relURL }} → "/hugo/mystyle.css"
{{ "http://gohugo.io/" | relURL }} → "http://gohugo.io/"
{{ "http://gohugo.io/" | absURL }} → "http://gohugo.io/"
```
The last two examples may look strange but can be very useful. For example, the following shows how to use `absURL` in [JSON-LD structured data (SEO)][jsonld], where some of your images for a piece of content may or may not be hosted locally:
{{< code file="layouts/partials/schemaorg-metadata.html" download="schemaorg-metadata.html" >}}
<script type="application/ld+json">
{
"@context" : "http://schema.org",
"@type" : "BlogPosting",
"image" : {{ apply .Params.images "absURL" "." }}
}
</script>
{{< /code >}}
The above uses the [apply function][] and also exposes how the Go template parser JSON-encodes objects inside `<script>` tags. See [the safeJS template function][safejs] for examples of how to tell Hugo not to escape strings inside of such tags.
{{% note "Ending Slash" %}}
`absURL` and `relURL` are smart about missing slashes, but they will *not* add a closing slash to a URL if it is not present.
{{% /note %}}
[apply function]: /functions/apply/
[configuration]: /getting-started/configuration/
[jsonld]: https://developers.google.com/search/docs/guides/intro-structured-data
[safejs]: /functions/safejs

View file

@ -0,0 +1,52 @@
---
title: .AddDate
description: Returns the time corresponding to adding the given number of years, months, and days passed to the function.
godocref: https://golang.org/pkg/time/#Time.AddDate
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [dates,time]
signature: [".AddDate YEARS MONTHS DAYS"]
workson: [times]
hugoversion:
relatedfuncs: [now]
deprecated: false
aliases: []
---
The `AddDate` function takes three arguments in logical order of `years`, `months`, and `days`.
## Example: Randomized Tweets from the Last 2 Years
Let's assume you have a file at `data/tweets.toml` that contains a list of Tweets to display on your site's homepage. The file is filled with `[[tweet]]` blocks; e.g.---
```
[[tweet]]
name = "Steve Francia"
twitter_handle = "@spf13"
quote = "I'm creator of Hugo. #metadocreference"
link = "https://twitter.com/spf13"
date = "2017-01-07T00:00:00Z"
```
Let's assume you want to grab Tweets from the last two years and present them in a random order. In conjunction with the [`where`](/functions/where/) and [`now`](/functions/now/) functions, you can limit our range to the last two years via `now.AddDate -2 0 0`, which represents a point in time 2 years, 0 days, and 0 hours before the time of your last site build.
{{< code file="partials/templates/random-tweets.html" download="tweets.html" >}}
{{ range where $.Site.Data.tweets.tweet "date" "ge" (now.AddDate -2 0 0) | shuffle }}
<div class="item">
<blockquote>
<p>
{{ .quote | safeHTML }}
</p>
&mdash; {{ .name }} ({{ .twitter_handle }}) <a href="{{ .link }}">
{{ dateFormat "January 2, 2006" .date }}
</a>
</blockquote>
</div>
{{ end }}
{{< /code >}}

View file

@ -0,0 +1,66 @@
---
title: after
description: "`after` slices an array to only the items after the <em>N</em>th item."
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [iteration]
signature: ["after INDEX COLLECTION"]
workson: []
hugoversion:
relatedfuncs: [last,first,seq]
deprecated: false
aliases: []
---
The following shows `after` being used in conjunction with the [`slice` function][slice]:
```
{{ $data := slice "one" "two" "three" "four" }}
{{ range after 2 $data }}
{{ . }}
{{ end }}
→ ["three", "four"]
```
## Example of `after` with `first`: 2nd&ndash;4th Most Recent Articles
You can use `after` in combination with the [`first` function][] and Hugo's [powerful sorting methods][lists]. Let's assume you have a list page at `example.com/articles`. You have 10 articles, but you want your templating for the [list/section page][] to show only two rows:
1. The top row is titled "Featured" and shows only the most recently published article (i.e. by `publishdate` in the content files' front matter).
2. The second row is titled "Recent Articles" and shows only the 2nd- to 4th-most recently published articles.
{{< code file="layouts/section/articles.html" download="articles.html" >}}
{{ define "main" }}
<section class="row featured-article">
<h2>Featured Article</h2>
{{ range first 1 .Data.Pages.ByPublishDate.Reverse }}
<header>
<h3><a href="{{.Permalink}}">{{.Title}}</a></h3>
</header>
<p>{{.Description}}</p>
{{ end }}
</section>
<div class="row recent-articles">
<h2>Recent Articles</h2>
{{ range first 3 (after 1 .Data.Pages.ByPublishDate.Reverse) }}
<section class="recent-article">
<header>
<h3><a href="{{.Permalink}}">{{.Title}}</a></h3>
</header>
<p>{{.Description}}</p>
</section>
{{ end }}
</div>
{{ end }}
{{< /code >}}
[`first` function]: /functions/first/
[list/section page]: /templates/section-templates/
[lists]: /lists/
[slice]: /functions/slice/

View file

@ -0,0 +1,119 @@
---
title: apply
description: Given a map, array, or slice, `apply` returns a new slice with a function applied over it.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [advanced]
signature: ["apply COLLETION FUNCTION [PARAM...]"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
draft: false
aliases: []
---
{{< todo >}}
<!-- POTENTIAL NEW CONTENT: see apply/sequence discussion: https://discourse.gohugo.io/t/apply-printf-on-a-sequence/5722; -->
{{< /todo >}}
`apply` expects at least three parameters, depending on the function being applied.
1. The first parameter is the sequence to operate on
2. The second parameter is the name of the function as a string, which must be the name of a valid [Hugo function][functions].
3. After that, the parameters to the applied function are provided, with the string `"."` standing in for each element of the sequence the function is to be applied against.
Here is an example of a content file with `name:` as a front matter field:
```
+++
names: [ "Derek Perkins", "Joe Bergevin", "Tanner Linsley" ]
+++
```
You can then use `apply` as follows:
```
{{ apply .Params.names "urlize" "." }}
```
Which will result as follows:
```
"derek-perkins", "joe-bergevin", "tanner-linsley"
```
This is *roughly* equivalent to using the following with [range][]
```
{{ range .Params.names }}{{ . | urlize }}{{ end }}
```
However, it isnt possible to provide the output of a range to the [`delimit` function][delimit], so you need to `apply` it.
If you have `post-tag-list.html` and `post-tag-link.html` as [partials][], you *could* use the following snippets, respectively:
{{< code file="layouts/partial/post-tag-list.html" copy="false" >}}
{{ with .Params.tags }}
<div class="tags-list">
Tags:
{{ $len := len . }}
{{ if eq $len 1 }}
{{ partial "post/tag/link" (index . 0) }}
{{ else }}
{{ $last := sub $len 1 }}
{{ range first $last . }}
{{ partial "post/tag/link" . }},
{{ end }}
{{ partial "post/tag/link" (index . $last) }}
{{ end }}
</div>
{{ end }}
{{< /code >}}
{{< code file="layouts/partial/post-tag-link.html" copy="false" >}}
<a class="post-tag post-tag-{{ . | urlize }}" href="/tags/{{ . | urlize }}">{{ . }}</a>
{{< /code >}}
This works, but the complexity of `post-tag-list.html` is fairly high. The Hugo template needs to perform special behavior for the case where theres only one tag, and it has to treat the last tag as special. Additionally, the tag list will be rendered something like `Tags: tag1 , tag2 , tag3` because of the way that the HTML is generated and then interpreted by a browser.
This first version of `layouts/partials/post-tag-list.html` separates all of the operations for ease of reading. The combined and DRYer version is shown next:
```
{{ with .Params.tags }}
<div class="tags-list">
Tags:
{{ $sort := sort . }}
{{ $links := apply $sort "partial" "post-tag-link" "." }}
{{ $clean := apply $links "chomp" "." }}
{{ delimit $clean ", " }}
</div>
{{ end }}
```
Now in the completed version, you can sort the tags, convert the tags to links with `layouts/partials/post-tag-link.html`, [chomp][] off stray newlines, and join the tags together in a delimited list for presentation. Here is an even DRYer version of the preceding example:
{{< code file="layouts/partials/post-tag-list.html" download="post-tag-list.html" >}}
{{ with .Params.tags }}
<div class="tags-list">
Tags:
{{ delimit (apply (apply (sort .) "partial" "post-tag-link" ".") "chomp" ".") ", " }}
</div>
{{ end }}
{{< /code >}}
{{% note %}}
`apply` does not work when receiving the sequence as an argument through a pipeline.
{{% /note %}}
[chomp]: /functions/chomp/ "See documentation for the chomp function"
[delimit]: /functions/delimit/ "See documentation for the delimit function"
[functions]: /functions/ "See the full list of Hugo functions to see what can be passed as an argument to the apply function."
[partials]: /templates/partials/
[range]: /functions/range/ "Learn the importance of the range function, a fundamental keyword in both Hugo templates and the Go programming language."

View file

@ -0,0 +1,51 @@
---
title: base64
description: "`base64Encode` and `base64Decode` let you easily decode content with a base64 encoding and vice versa through pipes."
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: []
relatedfuncs: []
signature: ["base64Decode INPUT", "base64Encode INPUT"]
workson: []
hugoversion:
deprecated: false
draft: false
aliases: []
---
An example:
{{< code file="base64-input.html" >}}
<p>Hello world = {{ "Hello world" | base64Encode }}</p>
<p>SGVsbG8gd29ybGQ = {{ "SGVsbG8gd29ybGQ=" | base64Decode }}</p>
{{< /code >}}
{{< output file="base-64-output.html" >}}
<p>Hello world = SGVsbG8gd29ybGQ=</p>
<p>SGVsbG8gd29ybGQ = Hello world</p>
{{< /output >}}
You can also pass other data types as arguments to the template function which tries to convert them. The following will convert *42* from an integer to a string because both `base64Encode` and `base64Decode` always return a string.
```
{{ 42 | base64Encode | base64Decode }}
=> "42" rather than 42
```
## `base64` with APIs
Using base64 to decode and encode becomes really powerful if we have to handle
responses from APIs.
```
{{ $resp := getJSON "https://api.github.com/repos/gohugoio/hugo/readme" }}
{{ $resp.content | base64Decode | markdownify }}
```
The response of the GitHub API contains the base64-encoded version of the [README.md](https://github.com/gohugoio/hugo/blob/master/README.md) in the Hugo repository. Now we can decode it and parse the Markdown. The final output will look similar to the rendered version on GitHub.

View file

@ -0,0 +1,24 @@
---
title: chomp
description: Removes any trailing newline characters.
godocref: Removes any trailing newline characters.
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [trim]
signature: ["chomp INPUT"]
workson: []
hugoversion:
relatedfuncs: [truncate]
deprecated: false
---
Useful in a pipeline to remove newlines added by other processing (e.g., [`markdownify`](/functions/markdownify/)).
```
{{chomp "<p>Blockhead</p>\n"}} → "<p>Blockhead</p>"
```

View file

@ -0,0 +1,28 @@
---
title: countrunes
description: Determines the number of runes in a string excluding any whitespace.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [counting, word count]
signature: ["countrunes INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: [/functions/countrunes/,/functions/countwords/]
---
In contrast with `countwords` function, which counts every word in a string, the `countrunes` function determines the number of runes in the content and excludes any whitespace. This has specific utility if you are dealing with CJK-like languages.
```
{{ "Hello, 世界" | countrunes }}
<!-- outputs a content length of 8 runes. -->
```
[pagevars]: /variables/page/

View file

@ -0,0 +1,29 @@
---
title: countwords
description: Counts the number of words in a string.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [counting, word count]
signature: ["countwords INPUT"]
workson: []
hugoversion:
relatedfuncs: [countrunes]
deprecated: false
aliases: [/functions/countrunes/,/functions/countwords/]
---
The template function works similar to the [.WordCount page variable][pagevars].
```
{{ "Hugo is a static site generator." | countwords }}
<!-- outputs a content length of 6 words. -->
```
[pagevars]: /variables/page/

View file

@ -0,0 +1,31 @@
---
title: dateFormat
description: Converts the textual representation of the `datetime` into the specified format.
godocref: https://golang.org/pkg/time/
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [dates,time,strings]
signature: ["dateFormat LAYOUT INPUT"]
workson: []
hugoversion:
relatedfuncs: [Format,now,Unix,time]
deprecated: false
---
`dateFormat` converts the textual representation of the `datetime` into the specified format or returns it as a Go `time.Time` type value. These are formatted with the layout string.
```
{{ dateFormat "Monday, Jan 2, 2006" "2015-01-21" }} → "Wednesday, Jan 21, 2015"
```
{{% warning %}}
As of v0.19 of Hugo, the `dateFormat` function is *not* supported as part of Hugo's [multilingual feature](/content-management/multilingual/).
{{% /warning %}}
See the [`Format` function](/functions/format/) for a more complete list of date formatting options in your templates.

View file

@ -0,0 +1,93 @@
---
title: default
description: Allows setting a default value that can be returned if a first value is not set.
qref: "Returns a default value if a value is not set when checked."
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
#tags: [defaults]
categories: [functions]
menu:
docs:
parent: "functions"
toc:
signature: ["default DEFAULT INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
draft: false
aliases: [/functions/default/]
needsexamples: false
---
`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 date type:
* non-zero for numeric types and times
* non-zero length for strings, arrays, slices, and maps
* any boolean or struct value
* non-nil for any other types
`default` function examples reference the following content page:
{{< code file="content/posts/default-function-example.md" >}}
---
title: Sane Defaults
seo_title:
date: 2017-02-18
font:
oldparam: The default function helps make your templating DRYer.
newparam:
---
{{< /code >}}
`default` can be written in more than one way:
```
{{ index .Params "font" | default "Roboto" }}
{{ default "Roboto" (index .Params "font") }}
```
Both of the above `default` function calls return `Roboto`.
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:
{{< code file="variable-as-default-value.html" nocopy="true" >}}
{{$old := .Params.oldparam }}
<p>{{ .Params.newparam | default $old }}</p>
{{< /code >}}
Which would return:
```
<p>The default function helps make your templating DRYer.</p>
```
And then using dot notation
{{< code file="dot-notation-default-value.html" >}}
<title>{{ .Params.seo_title | default .Title }}</title>
{{< /code >}}
Which would return
{{< output file="dot-notation-default-return-value.html" >}}
<title>Sane Defaults</title>
{{< /output >}}
The following have equivalent return values but are far less terse. This demonstrates the utility of `default`:
Using `if`:
{{< code file="if-instead-of-default.html" nocopy="true" >}}
<title>{{if .Params.seo_title}}{{.Params.seo_title}}{{else}}{{.Title}}{{end}}</title>
=> Sane Defaults
{{< /code >}}
Using `with`:
{{< code file="with-instead-of-default.html" nocopy="true" >}}
<title>{{with .Params.seo_title}}{{.}}{{else}}{{.Title}}{{end}}</title>
=> Sane Defaults
{{< /code >}}

View file

@ -0,0 +1,64 @@
---
title: delimit
description: Loops through any array, slice, or map and returns a string of all the values separated by a delimiter.
godocref:
workson: []
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [iteration]
toc: false
signature: ["delimit COLLECTION DELIMIT LAST"]
workson: [lists,taxonomies,terms]
hugoversion:
relatedfuncs: []
deprecated: false
draft: false
aliases: []
---
`delimit` called in your template takes the form of
```
{{ delimit array/slice/map delimiter optionallastdelimiter}}
```
`delimit` loops through any array, slice, or map and returns a string of all the values separated by a delimiter, the second argument in the function call. There is an optional third parameter that lets you choose a different delimiter to go between the last two values in the loop.
To maintain a consistent output order, maps will be sorted by keys and only a slice of the values will be returned.
The examples of `delimit` that follow all use the same front matter:
{{< code file="delimit-example-front-matter.toml" nocopy="true" >}}
+++
title: I love Delimit
#tags: [ "tag1", "tag2", "tag3" ]
+++
{{< /code >}}
{{< code file="delimit-page-tags-input.html" >}}
<p>Tags: {{ delimit .Params.tags ", " }}</p>
{{< /code >}}
{{< output file="delimit-page-tags-output.html" >}}
<p>Tags: tag1, tag2, tag3</p>
{{< /output >}}
Here is the same example but with the optional "last" delimiter:
{{< code file="delimit-page-tags-final-and-input.html" >}}
Tags: {{ delimit .Params.tags ", " ", and " }}
{{< /code >}}
{{< output file="delimit-page-tags-final-and-output.html" >}}
<p>Tags: tag1, tag2, and tag3</p>
{{< /output >}}
[lists]: /templates/lists/
[taxonomies]: /templates/taxonomy-templates/#taxonomy-list-templates
[terms]: /templates/taxonomy-templates/#terms-list-templates

View file

@ -0,0 +1,43 @@
---
title: dict
description: Creates a dictionary from a list of key and value pairs.
godocref:
workson: []
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-26
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [dictionary]
signature: ["dict KEY VALUE [KEY VALUE]..."]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
`dict` is especially useful for passing more than one value to a partial template.
## Example: `dict` with Embedded SVGs
The partial below creates a SVG and expects `fill` `height` and `width` from the caller:
{{< code file="layouts/partials/svgs/external-links.svg" download="external-links.svg" >}}
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="{{ .fill }}" width="{{ .size }}" height="{{ .size }}" viewBox="0 0 32 32" aria-label="External Link">
<path d="M25.152 16.576v5.696q0 2.144-1.504 3.648t-3.648 1.504h-14.848q-2.144 0-3.648-1.504t-1.504-3.648v-14.848q0-2.112 1.504-3.616t3.648-1.536h12.576q0.224 0 0.384 0.16t0.16 0.416v1.152q0 0.256-0.16 0.416t-0.384 0.16h-12.576q-1.184 0-2.016 0.832t-0.864 2.016v14.848q0 1.184 0.864 2.016t2.016 0.864h14.848q1.184 0 2.016-0.864t0.832-2.016v-5.696q0-0.256 0.16-0.416t0.416-0.16h1.152q0.256 0 0.416 0.16t0.16 0.416zM32 1.152v9.12q0 0.48-0.352 0.8t-0.8 0.352-0.8-0.352l-3.136-3.136-11.648 11.648q-0.16 0.192-0.416 0.192t-0.384-0.192l-2.048-2.048q-0.192-0.16-0.192-0.384t0.192-0.416l11.648-11.648-3.136-3.136q-0.352-0.352-0.352-0.8t0.352-0.8 0.8-0.352h9.12q0.48 0 0.8 0.352t0.352 0.8z"></path>
</svg>
{{< /code >}}
These values can be stored in one object with `dict` and passed to the partial:
{{< code file="layouts/_default/list.html" >}}
{{ partial "svg/link-ext.svg" (dict "fill" "#01589B" "size" 10 "width" 20 ) }}
{{< /code >}}
[partials]: /templates/partials/

View file

@ -0,0 +1,25 @@
---
title: echoParam
description: Prints a parameter if it is set.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: []
signature: ["echoParam DICTIONARY KEY"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
draft: false
aliases: []
---
```
{{ echoParam .Params "project_url" }}
```

View file

@ -0,0 +1,32 @@
---
title: emojify
description: Runs a string through the Emoji emoticons processor.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings,emojis]
signature: ["emojify INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
---
`emoji` runs a passed string through the Emoji emoticons processor.
See the [Emoji cheat sheet][emojis] for available emoticons.
The `emojify` function can be called in your templates but not directly in your content files by default. For emojis in content files, set `enableEmoji` to `true` in your site's [configuration][config]. Then you can write emoji shorthand directly into your content files; e.g. <code>I :</code><code>heart</code><code>: Hugo!</code>:
I :heart: Hugo!
[config]: /getting-started/configuration/
[emojis]: http://www.emoji-cheat-sheet.com/
[sc]: /templates/shortcode-templates/
[scsource]: https://github.com/gohugoio/hugo/tree/master/docs/layouts/shortcodes

View file

@ -0,0 +1,25 @@
---
title: eq
linktitle: eq
description: Returns the boolean truth of arg1 == arg2.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [operators,logic]
signature: ["eq ARG1 ARG2"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
```
{{ if eq .Section "blog" }}current{{ end }}
```

View file

@ -0,0 +1,47 @@
---
title: findRE
description: Returns a list of strings that match the regular expression.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [regex]
signature: ["findRE PATTERN INPUT [LIMIT]"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
By default all matches will be included. The number of matches can be limitted with an optional third parameter.
The example below returns a list of all second level headers (`<h2>`) in the content:
```
{{ findRE "<h2.*?>(.|\n)*?</h2>" .Content }}
```
You can limit the number of matches in the list with a third parameter. The following example shows how to limit the returned value to just one match (or none, if there are no matched substrings):
```
{{ findRE "<h2.*?>(.|\n)*?</h2>" .Content 1 }}
<!-- returns ["<h2 id="#foo">Foo</h2>"] -->
```
{{% note %}}
Hugo uses Golang's [Regular Expression package](https://golang.org/pkg/regexp/), which is the same general syntax used by Perl, Python, and other languages but with a few minor differences for those coming from a background in PCRE. For a full syntax listing, see the [GitHub wiki for re2](https://github.com/google/re2/wiki/Syntax).
If you are just learning RegEx, or at least Golang's flavor, you can practice pattern matching in the browser at <https://regex101.com/>.
{{% /note %}}
[partials]: /templates/partials/
[`plainify`]: /functions/plainify/
[toc]: /content-management/toc/
[`urlize`]: /functions/urlize

View file

@ -0,0 +1,28 @@
---
title: first
linktitle: first
description: "Slices an array to only the first _N_ elements."
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [iteration]
signature: ["first LIMIT COLLECTION"]
workson: [lists,taxonomies,terms,groups]
hugoversion:
relatedfuncs: [after,last]
deprecated: false
aliases: []
---
```
{{ range first 10 .Data.Pages }}
{{ .Render "summary" }}
{{ end }}
```

View file

@ -0,0 +1,126 @@
---
title: .Format
description: Formats built-in Hugo dates---`.Date`, `.PublishDate`, and `.LastMod`---according to Go's layout string.
godocref: https://golang.org/pkg/time/#example_Time_Format
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [dates,time]
signature: [".Format FORMAT"]
workson: [times]
hugoversion:
relatedfuncs: [dateFormat,now,Unix,time]
deprecated: false
aliases: []
toc: true
---
`.Format` will format date values defined in your front matter and can be used as a property on the following [page variables][pagevars]:
* `.PublishDate`
* `.Date`
* `.LastMod`
Assuming a key-value of `date: 2017-03-03` in a content file's front matter, your can run the date through `.Format` followed by a layout string for your desired output at build time:
```
{{ .PublishDate.Format "January 2, 2006" }} => March 3, 2017
```
For formatting *any* string representations of dates defined in your front matter, see the [`dateFormat` function][dateFormat], which will still leverage the Golang layout string explained below but uses a slightly different syntax.
## Go's Layout String
Hugo templates [format your dates][time] via layout strings that point to a specific reference time:
```
Mon Jan 2 15:04:05 MST 2006
```
While this may seem arbitrary, the numerical value of `MST` is `07`, thus making the layout string a sequence of numbers.
Here is a visual explanation [taken directly from the Go docs][gdex]:
```
Jan 2 15:04:05 2006 MST
=> 1 2 3 4 5 6 -7
```
### Hugo Date and Time Templating Reference
The following examples show the layout string followed by the rendered output.
The examples were rendered and tested in [CST][] and all point to the same field in a content file's front matter:
```
date: 2017-03-03T14:15:59-06:00
```
`.Date` (i.e. called via [page variable][pagevars])
: **Returns**: `2017-03-03 14:15:59 -0600 CST`
`"Monday, January 2, 2006"`
: **Returns**: `Friday, March 3, 2017`
`"Mon Jan 2 2006"`
: **Returns**: `Fri Mar 3 2017`
`"January 2nd"`
: **Returns**: `March 3rd`
`"January 2006"`
: **Returns**: `March 2017`
`"2006-01-02"`
: **Returns**: `2017-03-03`
`"Monday"`
: **Returns**: `Friday`
`"02 Jan 06 15:04 MST"` (RFC822)
: **Returns**: `03 Mar 17 14:15 CST`
`"02 Jan 06 15:04 -0700"` (RFC822Z)
: **Returns**: `03 Mar 17 14:15 -0600`
`"Mon, 02 Jan 2006 15:04:05 MST"` (RFC1123)
: **Returns**: `Fri, 03 Mar 2017 14:15:59 CST`
`"Mon, 02 Jan 2006 15:04:05 -0700"` (RFC339)
: **Returns**: `Fri, 03 Mar 2017 14:15:59 -0600`
### Cardinal Numbers and Ordinal Abbreviations
Spelled-out cardinal numbers (e.g. "one", "two", and "three") and ordinal abbreviations (i.e., with shorted suffixes like "1st", "2nd", and "3rd") are not currently supported:
```
{{.Date.Format "Jan 2nd 2006"}}
```
Hugo assumes you want to append `nd` as a string to the day of the month and outputs the following:
```
Mar 3nd 2017
```
<!-- Content idea: see https://discourse.gohugo.io/t/formatting-a-date-with-suffix-2nd/5701 -->
### Use `.Local` and `.UTC`
In conjunction with the [`dateFormat` function][dateFormat], you can also convert your dates to `UTC` or to local timezones:
`{{ dateFormat "02 Jan 06 15:04 MST" .Date.UTC }}`
: **Returns**: `03 Mar 17 20:15 UTC`
`{{ dateFormat "02 Jan 06 15:04 MST" .Date.Local }}`
: **Returns**: `03 Mar 17 14:15 CST`
[CST]: https://en.wikipedia.org/wiki/Central_Time_Zone
[dateFormat]: /functions/dateformat/
[gdex]: https://golang.org/pkg/time/#example_Time_Format
[pagevars]: /variables/page/
[time]: https://golang.org/pkg/time/

View file

@ -0,0 +1,25 @@
---
title: ge
linktitle: ge
description: Returns the boolean truth of arg1 >= arg2.
godocref:
date: 2017-07-26
publishdate: 2017-07-26
lastmod: 2017-07-26
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [operators,logic]
signature: ["ge ARG1 ARG2"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
```
{{ if ge 10 5 }}true{{ end }}
```

View file

@ -0,0 +1,32 @@
---
title: .Get
description: Accesses positional and ordered parameters in shortcode declaration.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [shortcodes]
signature: ["Get INDEX", "Get KEY"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
needsexample: true
---
`.Get` is specifically used when creating your own [shortcode template][sc].
[sc]: /templates/shortcode-templates/

View file

@ -0,0 +1,31 @@
---
title: getenv
description: Returns the value of an environment variable.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: []
signature: ["getenv VARIABLE"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
Takes a string containing the name of the variable as input. Returns
an empty string if the variable is not set, otherwise returns the
value of the variable.
```
{{ getenv "HOME" }}
```
{{% note %}}
In Unix-like environments, the variable must also be exported in order to be seen by `hugo`.
{{% /note %}}

View file

@ -0,0 +1,25 @@
---
title: gt
linktitle: gt
description: Returns the boolean truth of arg1 > arg2.
godocref:
date: 2017-07-26
publishdate: 2017-07-26
lastmod: 2017-07-26
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [operators,logic]
signature: ["gt ARG1 ARG2"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
```
{{ if gt 10 5 }}true{{ end }}
```

View file

@ -0,0 +1,22 @@
---
title: hasprefix
linktitle: hasPrefix
description: Tests whether a string begins with prefix.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: []
signature: ["hasPrefix STRING PREFIX"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
* `{{ hasPrefix "Hugo" "Hu" }}` → true

View file

@ -0,0 +1,23 @@
---
title: .HasChildren
description:
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [menus]
toc:
signature: ["HasChildren"]
workson: [menus]
hugoversion:
relatedfuncs: []
deprecated: false
draft: true
aliases: []
---
Used in [menu templates](/templates/menu-templates/).

View file

@ -0,0 +1,23 @@
---
title: .HasMenuCurrent
description:
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [menus]
signature: ["HasMenuCurrent"]
workson: [menus]
hugoversion:
relatedfuncs: []
deprecated: false
toc: false
draft: true
aliases: []
---
Used in [menu templates](/templates/menu-templates/).

View file

@ -0,0 +1,28 @@
---
title: highlight
linktitle: highlight
description: Takes a string of code and language declaration and uses Pygments to return syntax-highlighted HTML with inline-styles.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [highlighting,pygments,code blocks,syntax]
signature: ["highlight INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
---
[`highlight` is used in Hugo's built-in `highlight` shortcode][highlight].
See [Installing Hugo][installpygments] for more information on Pygments or [Syntax Highlighting][syntax] for more options on how to add syntax highlighting to your code blocks with Hugo.
[highlight]: /content-management/shortcodes/#highlight
[installpygments]: /getting-started/installing/#installing-pygments-optional
[syntax]: /tools/syntax-highlighting/

View file

@ -0,0 +1,26 @@
---
title: htmlEscape
linktitle:
description: Returns the given string with the reserved HTML codes escaped.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings, html]
signature: ["htmlEscape INPUT"]
workson: []
hugoversion:
relatedfuncs: [htmlUnescape]
deprecated: false
aliases: []
---
In the result `&` becomes `&amp;` and so on. It escapes only: `<`, `>`, `&`, `'` and `"`.
```
{{ htmlEscape "Hugo & Caddy > Wordpress & Apache" }} → "Hugo &amp; Caddy &gt; Wordpress &amp; Apache"
```

View file

@ -0,0 +1,28 @@
---
title: htmlUnescape
linktitle: htmlUnescape
description: Returns the given string with HTML escape codes un-escaped.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: []
signature: ["htmlUnescape INPUT"]
workson: []
hugoversion:
relatedfuncs: [htmlEscape]
deprecated: false
aliases: []
---
`htmlUnescape` returns the given string with HTML escape codes un-escaped.
Remember to pass the output of this to `safeHTML` if fully un-escaped characters are desired. Otherwise, the output will be escaped again as normal.
```
{{ htmlUnescape "Hugo &amp; Caddy &gt; Wordpress &amp; Apache" }} → "Hugo & Caddy > Wordpress & Apache"
```

View file

@ -0,0 +1,31 @@
---
title: humanize
linktitle:
description: Returns the humanized version of an argument with the first letter capitalized.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings,casing]
signature: ["humanize INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
If the input is either an int64 value or the string representation of an integer, humanize returns the number with the proper ordinal appended.
```
{{humanize "my-first-post"}} → "My first post"
{{humanize "myCamelPost"}} → "My camel post"
{{humanize "52"}} → "52nd"
{{humanize 103}} → "103rd"
```

View file

@ -0,0 +1,34 @@
---
title: i18n
linktitle: i18n
description: Translates a piece of content based on your i18n configuration files.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [internationalization,i18n,multilingual]
signature: ["i18n KEY", "T KEY"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
This translates a piece of content based on your `i18n/en-US.yaml` (and similar) files. You can use the [go-i18n](https://github.com/nicksnyder/go-i18n) tools to manage your translations. The translations can exist in both the theme and at the root of your repository.
```
{{ i18n "translation_id" }}
```
{{% note "Alias `T`" %}}
`T` is an alias to `i18n`. E.g. `{{ T "translation_id" }}`.
{{% /note %}}
For more information about string translations, see [Translation of Strings in Multilingual Mode][multistrings].
[multistrings]: /content-management/multilingual/#translation-of-strings

View file

@ -0,0 +1,24 @@
---
linktitle: imageConfig
description: Parses the image and returns the height, width, and color model.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [images]
signature: ["imageConfig PATH"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
---
```
{{ with (imageConfig "favicon.ico") }}
favicon.ico: {{.Width}} x {{.Height}}
{{ end }}
```

View file

@ -0,0 +1,33 @@
---
title: in
linktitle:
description: Checks if an element is in an array or slice--or a substring in a string---and returns a boolean.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings]
signature: ["in SET ITEM"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
The elements supported are strings, integers and floats, although only float64 will match as expected.
In addition, `in` can also check if a substring exists in a string.
```
{{ if in .Params.tags "Git" }}Follow me on GitHub!{{ end }}
```
```
{{ if in "this string contains a substring" "substring" }}Substring found!{{ end }}
```

View file

@ -0,0 +1,84 @@
---
title: index
linktitle: index
description: Looks up the index(es) or key(s) of the data structure passed into it.
godocref: https://golang.org/pkg/text/template/#hdr-Functions
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: []
signature: ["index COLLECTION INDEX", "index COLLECTION KEY"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: [/functions/index/]
needsexample: true
---
From the Godocs:
> Returns the result of indexing its first argument by the following arguments. Thus "index x 1 2 3" is, in Go syntax, x[1][2][3]. Each indexed item must be a map, slice, or array.
In Go templates, you can't access array, slice, or map elements directly the same way you would in Go. For example, `$.Site.Data.authors[.Params.authorkey]` isn't supported syntax.
Instead, you have to use `index`, a function that handles the lookup for you.
## Example: Load Data from a Path Based on Front Matter Params
Assume you want to add a `location = ""` field to your front matter for every article written in `content/vacations/`. You want to use this field to populate information about the location at the bottom of the article in your `single.html` template. You also have a directory in `data/locations/` that looks like the following:
```
.
└── data
└── locations
├── abilene.toml
├── chicago.toml
├── oslo.toml
└── provo.toml
```
Here is an example of the data inside `data/locations/oslo.toml`:
```
website = "https://www.oslo.kommune.no"
pop_city = 658390
pop_metro = 1717900
```
The example we will use will be an article on Oslo, which front matter should set to exactly the same name as the corresponding file name in `data/locations/`:
```
title = "My Norwegian Vacation"
location = "oslo"
```
The content of `oslo.toml` can be accessed from your template using the following node path: `.Site.Data.locations.oslo`. However, the specific file you need is going to change according to the front matter.
This is where the `index` function is needed. `index` takes 2 parameters in this use case:
1. The node path
2. A string corresponding to the desired data; e.g.&mdash;
```
{{ index .Site.Data.locations “oslo” }}
```
The variable for `.Params.location` is a string and can therefore replace `oslo` in the example above:
```
{{ index .Site.Data.authors .Params.author }}
=> map[website:https://www.oslo.kommune.no pop_city:658390 pop_metro:1717900]
```
Now the call will return the specific file according to the location specified in the content's front matter, but you will likely want to write specific properties to the template. You can do this by continuing down the node path via dot notation (`.`):
```
{{ (index .Site.Data.locations .Params.location).pop_city }}
=> 658390
```

View file

@ -0,0 +1,26 @@
---
title: int
linktitle: int
description: Creates an `int` from the argument passed into the function.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings,integers]
signature: ["int INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
Useful for turning strings into numbers.
```
{{ int "123" }} → 123
```

View file

@ -0,0 +1,56 @@
---
title: intersect
linktitle: intersect
description: Returns the common elements of two arrays or slices.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: []
signature: ["intersect SET1 SET2"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
The elements supported are strings, integers, and floats (only float64).
A useful example of `intersect` functionality is a "related posts" block. `isset` allows us to create a list of links to other posts that have tags that intersect with the tags in the current post.
The following is an example of a "related posts" [partial template][partials] that could be added to a [single page template][single]:
{{< code file="layouts/partials/related-posts.html" download="related-posts.html" >}}
<ul>
{{ $page_link := .Permalink }}
{{ $tags := .Params.tags }}
{{ range .Site.Pages }}
{{ $page := . }}
{{ $has_common_tags := intersect $tags .Params.tags | len | lt 0 }}
{{ if and $has_common_tags (ne $page_link $page.Permalink) }}
<li><a href="{{ $page.Permalink }}">{{ $page.Title }}</a></li>
{{ end }}
{{ end }}
</ul>
{{< /code >}}
This is also very useful to use as `AND` filters when combined with where:
```
{{ $pages := where .Site.RegularPages "Type" "not in" (slice "page" "about") }}
{{ $pages := $pages | union (where .Site.RegularPages "Params.pinned" true) }}
{{ $pages := $pages | intersect (where .Site.RegularPages "Params.images" "!=" nil) }}
```
The above fetches regular pages not of `page` or `about` type unless they are pinned. And finally, we exclude all pages with no `images` set in Page params.
See [union](/functions/union) for `OR`.
[partials]: /templates/partials/
[single]: /templates/single-page-templates/

View file

@ -0,0 +1,23 @@
---
title: .IsMenuCurrent
description:
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [menus]
signature: ["IsMenuCurrent"]
workson: [menus]
hugoversion:
relatedfuncs: []
deprecated: false
draft: true
aliases: []
needsexample: true
---
Used in [menu templates](/templates/menu-templates/).

View file

@ -0,0 +1,31 @@
---
title: isset
linktitle: isset
description: Returns true if the parameter is set.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: []
signature: ["isset COLLECTION INDEX", "isset COLLECTION KEY"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
Takes either a slice, array, or channel and an index or a map and a key as input.
```
{{ if isset .Params "project_url" }} {{ index .Params "project_url" }}{{ end }}
```
{{% warning %}}
All site-level configuration keys are stored as lower case. Therefore, a `myParam` key-value set in your [site configuration file](/getting-started/configuration/) needs to be accessed with `{{if isset .Site.Params "myparam"}}` and *not* with `{{if isset .Site.Params "myParam"}}`. Note that you can still access the same config key with `.Site.Params.myParam` *or* `.Site.Params.myparam`, for example, when using [`with`](/functions/with).
{{% /warning %}}

View file

@ -0,0 +1,28 @@
---
title: jsonify
linktitle: jsonify
description: Encodes a given object to JSON.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings,json]
signature: ["jsonify INPUT"]
workson: []
hugoversion:
relatedfuncs: [plainify]
deprecated: false
aliases: []
---
```
{{ dict "title" .Title "content" .Plain | jsonify }}
```
See also the `.PlainWords`, `.Plain`, and `.RawContent` [page variables][pagevars].
[pagevars]: /variables/page/

View file

@ -0,0 +1,30 @@
---
title: last
linktitle: last
description: "slices an array to only the last <em>N</em>th elements."
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
#tags: []
categories: [functions]
menu:
docs:
parent: "functions"
toc:
signature: ["last INDEX COLLECTION"]
workson: [lists, taxonomies, terms, groups]
hugoversion:
relatedfuncs: []
deprecated: false
draft: false
aliases: []
---
```
{{ range last 10 .Data.Pages }}
{{ .Render "summary" }}
{{ end }}
```

View file

@ -0,0 +1,25 @@
---
title: le
linktitle: le
description: Returns the boolean truth of arg1 <= arg2.
godocref:
date: 2017-07-26
publishdate: 2017-07-26
lastmod: 2017-07-26
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [operators,logic]
signature: ["le ARG1 ARG2"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
```
{{ if le 5 10 }}true{{ end }}
```

View file

@ -0,0 +1,60 @@
---
title: len
linktitle: len
description: Returns the length of a variable according to its type.
godocref: https://golang.org/pkg/builtin/#len
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-04-18
categories: [functions]
#tags: []
signature: ["len INPUT"]
workson: [lists,taxonomies,terms]
hugoversion:
relatedfuncs: []
deprecated: false
toc: false
aliases: []
---
`len` is a built-in function in Golang that returns the length of a variable according to its type. From the Golang documentation:
> Array: the number of elements in v.
>
> Pointer to array: the number of elements in *v (even if v is nil).
>
> Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
>
> String: the number of bytes in v.
>
> Channel: the number of elements queued (unread) in the channel buffer; if v is nil, len(v) is zero.
`len` is also considered a [fundamental function for Hugo templating][].
## `len` Example 1: Longer Headings
You may want to append a class to a heading according to the length of the string therein. The following templating checks to see if the title's length is greater than 80 characters and, if so, adds a `long-title` class to the `<h1>`:
{{< code file="check-title-length.html" >}}
<header>
<h1{{if gt (len .Title) 80}} class="long-title"{{end}}>{{.Title}}</h1>
</header>
{{< /code >}}
## `len` Example 2: Counting Pages with `where`
The following templating uses [`where`][] in conjunction with `len` to figure out the total number of content pages in a `posts` [section][]:
{{< code file="how-many-posts.html" >}}
{{ $posts := (where .Site.RegularPages "Section" "==" "post") }}
{{ $postCount := len $posts }}
{{< /code >}}
Note the use of `.RegularPages`, a [site variable][] that counts all regular content pages but not the `_index.md` pages used to add front matter and content to [list templates][].
[fundamental function for Hugo templating]: /templates/introduction/
[list templates]: /templates/lists/
[section]: /content-management/sections/
[site variable]: /variables/site/
[`where`]: /functions/where/

View file

@ -0,0 +1,24 @@
---
title: lower
linktitle: lower
description: Converts all characters in the provided string to lowercase.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings,casing]
signature: ["lower INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
```
{{lower "BatMan"}} → "batman"
```

View file

@ -0,0 +1,25 @@
---
title: lt
linktitle: lt
description: Returns the boolean truth of arg1 < arg2.
godocref:
date: 2017-07-26
publishdate: 2017-07-26
lastmod: 2017-07-26
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [operators,logic]
signature: ["lt ARG1 ARG2"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
```
{{ if lt 5 10 }}true{{ end }}
```

View file

@ -0,0 +1,25 @@
---
title: markdownify
linktitle: markdownify
description: Runs the provided string through the Markdown processor.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
#tags: [markdown,content]
categories: [functions]
menu:
docs:
parent: "functions"
signature: ["markdownify INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
```
{{ .Title | markdownify }}
```

View file

@ -0,0 +1,65 @@
---
title: Math
description: Hugo provides six mathematical operators in templates.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
#tags: [math, operators]
categories: [functions]
menu:
docs:
parent: "functions"
toc:
signature: []
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
draft: false
aliases: []
---
There are 6 basic mathematical operators that can be used in Hugo templates:
| Function | Description | Example |
| -------- | ------------------------ | ----------------------------- |
| `add` | Adds two integers. | `{{add 1 2}}` &rarr; 3 |
| `div` | Divides two integers. | `{{div 6 3}}` &rarr; 2 |
| `mod` | Modulus of two integers. | `{{mod 15 3}}` &rarr; 0 |
| `modBool`| Boolean of modulus of two integers. Evaluates to `true` if = 0. | `{{modBool 15 3}}` &rarr; true |
| `mul` | Multiplies two integers. | `{{mul 2 3}}` &rarr; 6 |
| `sub` | Subtracts two integers. | `{{sub 3 2}}` &rarr; 1 |
## Use `add` with Strings
You can also use the `add` function with strings. You may like this functionality in many use cases, including creating new variables by combining page- or site-level variables with other strings.
For example, social media sharing with [Twitter Cards][cards] requires the following `meta` link in your site's `<head>` to display Twitter's ["Summary Card with Large Image"][twtsummary]:
```
<meta name="twitter:image" content="https://example.com/images/my-twitter-image.jpg">
```
Let's assume you have an `image` field in the front matter of each of your content files:
```
---
title: My Post
image: my-post-image.jpg
---
```
You can then concatenate the `image` value (string) with the path to your `images` directory in `static` and leverage a URL-related templating function for increased flexibility:
{{< code file="partials/head/twitter-card.html" >}}
{{$socialimage := add "images/" .Params.image}}
<meta name="twitter:image" content="{{ $socialimage | absURL }}">
{{< /code >}}
{{% note %}}
The `add` example above makes use of the [`absURL` function](/functions/absurl/). `absURL` and its relative companion `relURL` is the recommended way to construct URLs in Hugo.
{{% /note %}}
[cards]: https://dev.twitter.com/cards/overview
[twtsummary]: https://dev.twitter.com/cards/types/summary-large-image

View file

@ -0,0 +1,33 @@
---
title: md5
linktitle: md5
description: hashes the given input and returns its MD5 checksum.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: []
signature: ["md5 INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
```
{{ md5 "Hello world, gophers!" }}
<!-- returns the string "b3029f756f98f79e7f1b7f1d1f0dd53b" -->
```
This can be useful if you want to use [Gravatar](https://en.gravatar.com/) for generating a unique avatar:
```
<img src="https://www.gravatar.com/avatar/{{ md5 "your@email.com" }}?s=100&d=identicon">
```

View file

@ -0,0 +1,25 @@
---
title: ne
linktitle: ne
description: Returns the boolean truth of arg1 != arg2.
godocref:
date: 2017-07-26
publishdate: 2017-07-26
lastmod: 2017-07-26
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [operators,logic]
signature: ["ne ARG1 ARG2"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
```
{{ if ne .Section "blog" }}current{{ end }}
```

View file

@ -0,0 +1,44 @@
---
title: now
linktitle: now
description: Returns the current local time
godocref: https://godoc.org/time#Time
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-04-30
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [dates,time]
signature: ["now"]
workson: []
hugoversion:
relatedfuncs: [Unix,dateFormat]
deprecated: false
aliases: []
---
See [`time.Time`](https://godoc.org/time#Time).
For example, building your site on June 24, 2017 with the following templating:
```
<div>
<small>&copy; {{ now.Format "2006"}}</small>
</div>
```
Which will produce the following:
```
<div>
<small>&copy; 2017</small>
</div>
```
The above example uses the [`.Format` function](/functions/format), which page includes a full listing of date formatting using Golang's layout string.
{{% note %}}
Older Hugo themes may use the deprecated `.Now` (uppercase). Be sure to use the lowercase `.now` in your templating.
{{% /note %}}

View file

@ -0,0 +1,41 @@
---
title: .Param
description: Calls page or site variables into your template.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-04-30
#tags: ["front matter"]
categories: [functions]
menu:
docs:
parent: "functions"
toc:
signature: [".Param KEY"]
workson: []
hugoversion:
relatedfuncs: [default]
deprecated: false
draft: false
aliases: []
---
In Hugo, you can declare [site-wide params][sitevars] (i.e. in your [configuration][]), as well as params for [individual pages][pagevars].
A common use case is to have a general value for the site and a more specific value for some of the pages (e.g., an image).
You can use the `.Param` method to call these values into your template. The following will first look for an `image` param in a specific content's [front matter][]. If not found, Hugo will look for an `image` param in your site's configuration:
```
$.Param "image"
```
{{% note %}}
The `Param` method may not consider empty strings in a content's front matter as "not found." If you are setting preconfigured front matter fields to empty strings using Hugo's archetypes, it may be best to use the [`default` function](/functions/default/) instead of `Param`. See the [related issue on GitHub](https://github.com/gohugoio/hugo/issues/3366).
{{% /note %}}
[configuration]: /getting-started/configuration/
[front matter]: /content-management/front-matter/
[pagevars]: /variables/page/
[sitevars]: /variables/site/

View file

@ -0,0 +1,40 @@
---
title: partialCached
linktitle: partialCached
description: Allows for caching of partials that do not need to be re-rendered on every invocation.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: []
signature: ["partialCached LAYOUT INPUT [VARIANT...]"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
The `partialCached` template function can offer significant performance gains for complex templates that don't need to be re-rendered on every invocation. Here is the simplest usage:
```
{{ partialCached "footer.html" . }}
```
You can also pass additional parameters to `partialCached` to create *variants* of the cached partial. For example, if you have a complex partial that should be identical when rendered for pages within the same section, you could use a variant based upon section so that the partial is only rendered once per section:
{{< code file="partial-cached-example.html" >}}
{{ partialCached "footer.html" . .Section }}
{{< /code >}}
If you need to pass additional parameters to create unique variants, you can pass as many variant parameters as you need:
```
{{ partialCached "footer.html" . .Params.country .Params.province }}
```
Note that the variant parameters are not made available to the underlying partial template. They are only use to create a unique cache key.

View file

@ -0,0 +1,31 @@
---
title: plainify
linktitle: plainify
description: Strips any HTML and returns the plain text version of the provided string.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-04-30
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings]
signature: ["plainify INPUT"]
workson: []
hugoversion:
relatedfuncs: [jsonify,]
deprecated: false
aliases: []
---
```
{{ "<b>BatMan</b>" | plainify }} → "BatMan"
```
See also the `.PlainWords`, `.Plain`, and `.RawContent` [page variables][pagevars].
[pagevars]: /variables/page/

View file

@ -0,0 +1,25 @@
---
title: pluralize
linktitle: pluralize
description: Pluralizes the given word according to a set of common English pluralization rules
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings]
signature: ["pluralize INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
```
{{ "cat" | pluralize }} → "cats"
```

View file

@ -0,0 +1,29 @@
---
title: printf
linktitle: printf
description: Formats a string using the standard `fmt.Sprintf` function.
godocref: https://golang.org/pkg/fmt/
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings]
signature: ["printf FORMAT INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
---
See [the go doc](https://golang.org/pkg/fmt/) for additional information.
```
{{ i18n ( printf "combined_%s" $var ) }}
```
```
{{ printf "formatted %.2f" 3.1416 }}
```

View file

@ -0,0 +1,34 @@
---
title: querify
linktitle: querify
description: Takes a set of key-value pairs and returns a query string to be appended to URLs.
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [urls]
godocref:
signature: ["querify KEY VALUE [KEY VALUE]..."]
hugoversion:
deprecated: false
workson: []
relatedfuncs: []
aliases: []
---
`querify` takes a set of key-value pairs and returns a [query string](https://en.wikipedia.org/wiki/Query_string) that can be appended to a URL. E.g.
The following example creates a link to a search results page on Google.
```
<a href="https://www.google.com?{{ (querify "q" "test" "page" 3) | safeURL }}">Search</a>
```
This example renders the following HTML:
```
<a href="https://www.google.com?page=3&q=test">Search</a>
```

View file

@ -0,0 +1,25 @@
---
title: range
linktitle:
description: Iterates over a map, array, or slice.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions,fundamentals]
menu:
docs:
parent: "functions"
#tags: [iteration]
signature: ["range COLLECTION"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
draft: false
aliases: []
---
Just like in the Go programming language, Go and Hugo templates make heavy use of `range` to iterate over a map, array or slice.
`range` is fundamental to templating in Hugo. (See the [Introduction to Hugo Templates](/templates/introduction/) for more examples.

View file

@ -0,0 +1,30 @@
---
title: readDir
description: Gets a directory listing from a directory relative to the current working directory.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [files]
signature: ["readDir PATH"]
workson: []
hugoversion:
relatedfuncs: [readFile]
deprecated: false
aliases: []
---
If your current project working directory has a single file named `README.txt`:
```
{{ range (readDir ".") }}{{ .Name }}{{ end }} → "README.txt"
```
For more information on using `readDir` and `readFile` in your templates, see [Local File Templates][local].
[local]: /templates/files/

View file

@ -0,0 +1,31 @@
---
title: readFile
description: Reads a file from disk relative to the current project working directory and returns a string.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-04-30
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [files]
signature: ["readFile PATH"]
workson: []
hugoversion:
relatedfuncs: [readDir]
deprecated: false
aliases: []
---
Note that the filename must be relative to the current project working directory.
So, if you have a file with the name `README.txt` in the root of your project with the content `Hugo Rocks!`:
```
{{readFile "README.txt"}} → "Hugo Rocks!"
```
For more information on using `readDir` and `readFile` in your templates, see [Local File Templates][local].
[local]: /templates/files/

View file

@ -0,0 +1,30 @@
---
title: ref
linktitle: ref
description: Looks up a content page by logical name.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [cross references, anchors]
signature: ["ref PAGE CONTENT"]
workson: []
hugoversion:
relatedfuncs: [relref]
deprecated: false
aliases: []
---
`ref` and `relRef` look up a content page by relative path (`relref`) or logical name (`ref`) to return the permalink. Both functions require a `Page` object (usually satisfied with a "`.`"):
```
{{ relref . "about.md" }}
```
These functions are used in two of Hugo's built-in shortcodes. You can see basic usage examples of both `ref` and `relref` in the [shortcode documentation](/content-management/shortcodes/#ref-and-relref).
For an extensive explanation of how to leverage `ref` and `relref` for content management, see [Cross References](/content-management/cross-references/).

View file

@ -0,0 +1,30 @@
---
title: relLangURL
description: Adds the relative URL with correct language prefix according to site configuration for multilingual.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
#tags: [multilingual,i18n,urls]
categories: [functions]
menu:
docs:
parent: "functions"
signature: ["relLangURL INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
`absLangURL` and `relLangURL` functions are similar to their [`absURL`](/functions/absurl/) and [`relURL`](/functions/relurl/) relatives but will add the correct language prefix when the site is configured with more than one language. (See [Configuring Multilingual][multiliconfig].)
So for a site `baseURL` set to `https://example.com/hugo/` and the current language is `en`:
```
{{ "blog/" | absLangURL }} → "https://example.com/hugo/en/blog/"
{{ "blog/" | relLangURL }} → "/hugo/en/blog/"
```
[multiliconfig]: /content-management/multilingual/#configuring-multilingual-mode

View file

@ -0,0 +1,30 @@
---
title: relref
# linktitle: relref
description: Looks up a content page by relative path.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [cross references, anchors]
signature: ["relref PAGE CONTENT"]
workson: []
hugoversion:
relatedfuncs: [relref]
deprecated: false
aliases: []
---
`ref` and `relRef` look up a content page by relative path (`relref`) or logical name (`ref`) to return the permalink. Both functions require a `Page` object (usually satisfied with a "`.`"):
```
{{ relref . "about.md" }}
```
These functions are used in two of Hugo's built-in shortcodes. You can see basic usage examples of both `ref` and `relref` in the [shortcode documentation](/content-management/shortcodes/#ref-and-relref).
For an extensive explanation of how to leverage `ref` and `relref` for content management, see [Cross References](/content-management/cross-references/).

View file

@ -0,0 +1,51 @@
---
title: relURL
description: Given a string, prepends the relative URL according to a page's position in the project directory structure.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [urls]
signature: ["relURL INPUT"]
workson: []
hugoversion:
relatedfuncs: [absURL]
deprecated: false
aliases: []
---
Both `absURL` and `relURL` consider the configured value of `baseURL` in your site's [`config` file][configuration]. Given a `baseURL` set to `https://example.com/hugo/`:
```
{{ "mystyle.css" | absURL }} → "https://example.com/hugo/mystyle.css"
{{ "mystyle.css" | relURL }} → "/hugo/mystyle.css"
{{ "http://gohugo.io/" | relURL }} → "http://gohugo.io/"
{{ "http://gohugo.io/" | absURL }} → "http://gohugo.io/"
```
The last two examples may look strange but can be very useful. For example, the following shows how to use `absURL` in [JSON-LD structured data for SEO][jsonld] where some of your images for a piece of content may or may not be hosted locally:
{{< code file="layouts/partials/schemaorg-metadata.html" download="schemaorg-metadata.html" >}}
<script type="application/ld+json">
{
"@context" : "http://schema.org",
"@type" : "BlogPosting",
"image" : {{ apply .Params.images "absURL" "." }}
}
</script>
{{< /code >}}
The above uses the [apply function][] and also exposes how the Go template parser JSON-encodes objects inside `<script>` tags. See [the safeJS template function][safejs] for examples of how to tell Hugo not to escape strings inside of such tags.
{{% note "Ending Slash" %}}
`absURL` and `relURL` are smart about missing slashes, but they will *not* add a closing slash to a URL if it is not present.
{{% /note %}}
[apply function]: /functions/apply/
[configuration]: /getting-started/configuration/
[jsonld]: https://developers.google.com/search/docs/guides/intro-structured-data
[safejs]: /functions/safejs

View file

@ -0,0 +1,34 @@
---
title: render
# linktitle: Render
description: Takes a view to apply when rendering content.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [views]
signature: ["render LAYOUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
The view is an alternative layout and should be a file name that points to a template in one of the locations specified in the documentation for [Content Views](/templates/views).
This function is only available when applied to a single piece of content within a [list context][].
This example could render a piece of content using the content view located at `/layouts/_default/summary.html`:
```
{{ range .Data.Pages }}
{{ .Render "summary"}}
{{ end }}
```
[list context]: /templates/lists/

View file

@ -0,0 +1,26 @@
---
title: replace
# linktitle: replace
description: Replaces all occurrences of the search string with the replacement string.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: []
signature: ["replace INPUT OLD NEW"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
```
`{{ replace "Batman and Robin" "Robin" "Catwoman" }}`
→ "Batman and Catwoman"
```

View file

@ -0,0 +1,31 @@
---
title: replaceRE
# linktitle: replaceRE
description: Replaces all occurrences of a regular expression with the replacement pattern.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-04-30
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [regex]
signature: ["replaceRE PATTERN REPLACEMENT INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
```
{{ replaceRE "^https?://([^/]+).*" "$1" "http://gohugo.io/docs" }}` → "gohugo.io"
{{ "http://gohugo.io/docs" | replaceRE "^https?://([^/]+).*" "$1" }}` → "gohugo.io"
```
{{% note %}}
Hugo uses Golang's [Regular Expression package](https://golang.org/pkg/regexp/), which is the same general syntax used by Perl, Python, and other languages but with a few minor differences for those coming from a background in PCRE. For a full syntax listing, see the [GitHub wiki for re2](https://github.com/google/re2/wiki/Syntax).
If you are just learning RegEx, or at least Golang's flavor, you can practice pattern matching in the browser at <https://regex101.com/>.
{{% /note %}}

View file

@ -0,0 +1,36 @@
---
title: safeCSS
description: Declares the provided string as a known "safe" CSS string.
godocref: https://golang.org/src/html/template/content.go?s=919:929#L15
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-26
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [style,css,strings]
signature: ["safeCSS INPUT"]
workson: []
hugoversion:
relatedfuncs: [safeHTML,safeHTMLAttr,]
deprecated: false
aliases: []
---
In this context, *safe* means CSS content that matches any of the following:
1. The CSS3 stylesheet production, such as `p { color: purple }`.
2. The CSS3 rule production, such as `a[href=~"https:"].foo#bar`.
3. CSS3 declaration productions, such as `color: red; margin: 2px`.
4. The CSS3 value production, such as `rgba(0, 0, 255, 127)`.
Example: Given `style = "color: red;"` defined in the front matter of your `.md` file:
* <span class="good">`<p style="{{ .Params.style | safeCSS }}">…</p>` &rarr; `<p style="color: red;">…</p>`</span>
* <span class="bad">`<p style="{{ .Params.style }}">…</p>` &rarr; `<p style="ZgotmplZ">…</p>`</span>
{{% note "ZgotmplZ" %}}
"ZgotmplZ" is a special value that indicates that unsafe content reached a CSS or URL context.
{{% /note %}}

View file

@ -0,0 +1,41 @@
---
title: safeHTML
# linktitle:
description: Declares a provided string as a "safe" HTML document to avoid escaping by Go templates.
godocref: https://golang.org/src/html/template/content.go?s=1374:1385#L25
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings]
signature: ["safeHTML INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
---
It should not be used for HTML from a third-party, or HTML with unclosed tags or comments.
Given a site-wide [`config.toml`][config] with the following `copyright` value:
```
copyright = "© 2015 Jane Doe. <a href=\"http://creativecommons.org/licenses/by/4.0/\">Some rights reserved</a>."
```
`{{ .Site.Copyright | safeHTML }}` in a template would then output:
```
© 2015 Jane Doe. <a href="http://creativecommons.org/licenses/by/4.0/">Some rights reserved</a>.
```
However, without the `safeHTML` function, html/template assumes `.Site.Copyright` to be unsafe and therefore escapes all HTML tags and renders the whole string as plain text:
```
<p>© 2015 Jane Doe. &lt;a href=&#34;http://creativecommons.org/licenses by/4.0/&#34;&gt;Some rights reserved&lt;/a&gt;.</p>
```
[config]: /getting-started/configuration/

View file

@ -0,0 +1,32 @@
---
title: safeHTMLAttr
# linktitle: safeHTMLAttr
description: Declares the provided string as a safe HTML attribute.
godocref: https://golang.org/src/html/template/content.go?s=1661:1676#L33
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings]
signature: ["safeHTMLAttr INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
Example: Given a site-wide `config.toml` that contains this menu entry:
```
[[menu.main]]
name = "IRC: #golang at freenode"
url = "irc://irc.freenode.net/#golang"
```
* <span class="bad">`<a href="{{ .URL }}">` &rarr; `<a href="#ZgotmplZ">`</span>
* <span class="good">`<a {{ printf "href=%q" .URL | safeHTMLAttr }}>` &rarr; `<a href="irc://irc.freenode.net/#golang">`</span>

View file

@ -0,0 +1,31 @@
---
title: safeJS
# linktitle:
description: Declares the provided string as a known safe JavaScript string.
godocref: https://golang.org/src/html/template/content.go?s=2548:2557#L51
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings]
signature: ["safeJS INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
draft: false
aliases: []
---
In this context, *safe* means the string encapsulates a known safe EcmaScript5 Expression (e.g., `(x + y * z())`).
Template authors are responsible for ensuring that typed expressions do not break the intended precedence and that there is no statement/expression ambiguity as when passing an expression like `{ foo:bar() }\n['foo']()`, which is both a valid expression and a valid program with a very different meaning.
Example: Given `hash = "619c16f"` defined in the front matter of your `.md` file:
* <span class="good">`<script>var form_{{ .Params.hash | safeJS }};…</script>` &rarr; `<script>var form_619c16f;…</script>`</span>
* <span class="bad">`<script>var form_{{ .Params.hash }};…</script>` &rarr; `<script>var form_"619c16f";…</script>`</span>

View file

@ -0,0 +1,72 @@
---
title: safeURL
description: Declares the provided string as a safe URL or URL substring.
godocref: https://golang.org/pkg/html/template/#HTMLEscape
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
#tags: [strings,urls]
categories: [functions]
menu:
docs:
parent: "functions"
signature: ["safeURL INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
`safeURL` declares the provided string as a "safe" URL or URL substring (see [RFC 3986][]). A URL like `javascript:checkThatFormNotEditedBeforeLeavingPage()` from a trusted source should go in the page, but by default dynamic `javascript:` URLs are filtered out since they are a frequently exploited injection vector.
Without `safeURL`, only the URI schemes `http:`, `https:` and `mailto:` are considered safe by Go templates. If any other URI schemes (e.g., `irc:` and `javascript:`) are detected, the whole URL will be replaced with `#ZgotmplZ`. This is to "defang" any potential attack in the URL by rendering it useless.
The following examples use a [site `config.toml`][configuration] with the following [menu entry][menus]:
{{< code file="config.toml" copy="false" >}}
[[menu.main]]
name = "IRC: #golang at freenode"
url = "irc://irc.freenode.net/#golang"
{{< /code >}}
The following is an example of a sidebar partial that may be used in conjunction with the preceding front matter example:
{{< code file="layouts/partials/bad-url-sidebar-menu.html" copy="false" >}}
<!-- This unordered list may be part of a sidebar menu -->
<ul>
{{ range .Site.Menus.main }}
<li><a href="{{ .URL }}">{{ .Name }}</a></li>
{{ end }}
</ul>
{{< /code >}}
This partial would produce the following HTML output:
{{< output file="bad-url-sidebar-menu-output.html" >}}
<!-- This unordered list may be part of a sidebar menu -->
<ul>
<li><a href="#ZgotmplZ">IRC: #golang at freenode</a></li>
</ul>
{{< /output >}}
The odd output can be remedied by adding ` | safeURL` to our `.Title` page variable:
{{< code file="layouts/partials/correct-url-sidebar-menu.html" copy="false" >}}
<!-- This unordered list may be part of a sidebar menu -->
<ul>
<li><a href="{{ .URL | safeURL }}">{{ .Name }}</a></li>
</ul>
{{< /code >}}
With the `.URL` page variable piped through `safeURL`, we get the desired output:
{{< output file="correct-url-sidebar-menu-output.html" >}}
<ul class="sidebar-menu">
<li><a href="irc://irc.freenode.net/#golang">IRC: #golang at freenode</a></li>
</ul>
{{< /output >}}
[configuration]: /getting-started/configuration/
[menus]: /content-management/menus/
[RFC 3986]: http://tools.ietf.org/html/rfc3986

View file

@ -0,0 +1,79 @@
---
title: .Scratch
description: Acts as a "scratchpad" to allow for writable page- or shortcode-scoped variables.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
#tags: [iteration]
categories: [functions]
menu:
docs:
parent: "functions"
toc:
signature: []
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
draft: false
aliases: [/extras/scratch/,/doc/scratch/]
---
In most cases you can do well without `Scratch`, but there are some use cases that aren't solvable with Go's templates without `Scratch`'s help, due to scoping issues.
{{% note %}}
See [this Go issue](https://github.com/golang/go/issues/10608) for the main motivation behind Scratch.
{{% /note %}}
`Scratch` is added to both `Page` and `Shortcode` -- with following methods:
* `Set` and `Add` takes a `key` and the `value` to add.
* `Get` returns the `value` for the `key` given.
* `SetInMap` takes a `key`, `mapKey` and `value`
* `GetSortedMapValues` returns array of values from `key` sorted by `mapKey`
`Set` and `SetInMap` can store values of any type.
For single values, `Add` accepts values that support Go's `+` operator. If the first `Add` for a key is an array or slice, the following adds will be appended to that list.
The scope of the backing data is global for the given `Page` or `Shortcode`, and spans partial and shortcode includes.
Note that `.Scratch` from a shortcode will return the shortcode's `Scratch`, which in most cases is what you want. If you want to store it in the page scroped Scratch, then use `.Page.Scratch`.
## Sample usage
The usage is best illustrated with some samples:
```
{{ $.Scratch.Add "a1" 12 }}
{{ $.Scratch.Get "a1" }} {{/* => 12 */}}
{{ $.Scratch.Add "a1" 1 }}
{{ $.Scratch.Get "a1" }} // {{/* => 13 */}}
{{ $.Scratch.Add "a2" "AB" }}
{{ $.Scratch.Get "a2" }} {{/* => AB */}}
{{ $.Scratch.Add "a2" "CD" }}
{{ $.Scratch.Get "a2" }} {{/* => ABCD */}}
{{ $.Scratch.Add "l1" (slice "A" "B") }}
{{ $.Scratch.Get "l1" }} {{/* => [A B] */}}
{{ $.Scratch.Add "l1" (slice "C" "D") }}
{{ $.Scratch.Get "l1" }} {{/* => [A B C D] */}}
{{ $.Scratch.Set "v1" 123 }}
{{ $.Scratch.Get "v1" }} {{/* => 123 */}}
{{ $.Scratch.SetInMap "a3" "b" "XX" }}
{{ $.Scratch.SetInMap "a3" "a" "AA" }}
{{ $.Scratch.SetInMap "a3" "c" "CC" }}
{{ $.Scratch.SetInMap "a3" "b" "BB" }}
{{ $.Scratch.GetSortedMapValues "a3" }} {{/* => []interface {}{"AA", "BB", "CC"} */}}
```
{{% note %}}
The examples above uses the special `$` variable, which refers to the top-level node. This is the behavior you most likely want, and will help remove some confusion when using `Scratch` inside page range loops -- and you start inadvertently calling the wrong `Scratch`. But there may be use cases for `{{ .Scratch.Add "key" "some value" }}`.
{{% /note %}}
[pagevars]: /variables/page/

View file

@ -0,0 +1,51 @@
---
title: seq
# linktitle:
description: Creates a sequence of integers.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: []
signature: ["seq LAST", "seq FIRST LAST", "seq FIRST INCREMENT LAST"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
draft: false
aliases: []
---
It's named and used in the model of [GNU's seq][].
```
3 → 1, 2, 3
1 2 4 → 1, 3
-3 → -1, -2, -3
1 4 → 1, 2, 3, 4
1 -2 → 1, 0, -1, -2
```
## Example: `seq` with `range` and `after`
You can use `seq` in combination with `range` and `after`. The following will return 19 elements:
```
{{ range after 1 (seq 20)}}
{{ end }}
```
However, when ranging with an index, the following may be less confusing in that `$indexStartingAt1` and `$num` will return `1,2,3 ... 20`:
```
{{ range $index, $num := (seq 20) }}
$indexStartingAt1 := (add $index 1)
{{ end }}
```
[GNU's seq]: http://www.gnu.org/software/coreutils/manual/html_node/seq-invocation.html#seq-invocation

View file

@ -0,0 +1,34 @@
---
title: sha
# linktitle: sha
description: Hashes the given input and returns either an SHA1 or SHA256 checksum.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [sha,checksum]
signature: ["sha1 INPUT", "sha256 INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
`sha1` hashes the given input and returns its SHA1 checksum.
```
{{ sha1 "Hello world, gophers!" }}
<!-- returns the string "c8b5b0e33d408246e30f53e32b8f7627a7a649d4" -->
```
`sha256` hashes the given input and returns its SHA256 checksum.
```
{{ sha256 "Hello world, gophers!" }}
<!-- returns the string "6ec43b78da9669f50e4e422575c54bf87536954ccd58280219c393f2ce352b46" -->
```

View file

@ -0,0 +1,39 @@
---
title: shuffle
# linktitle:
description: Returns a random permutation of a given array or slice.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-04-30
#tags: [ordering]
categories: [functions]
menu:
docs:
parent: "functions"
signature: ["shuffle COLLECTION"]
workson: []
hugoversion:
relatedfuncs: [seq]
deprecated: false
draft: false
aliases: []
---
{{< code file="shuffle-input.html" >}}
<!-- Shuffled sequence = -->
<div>{{ shuffle (seq 1 5) }}</div>
<!-- Shuffled slice = -->
<div>{{ shuffle (slice "foo" "bar" "buzz") }}</div>
{{< /code >}}
This example would return the following:
{{< output file="shuffle-output.html" >}}
<!-- Shuffled sequence = -->
<div>2 5 3 1 4</div>
<!-- Shuffled slice = -->
<div>buzz foo bar</div>
{{< /output >}}
This example also makes use of the [slice](/functions/slice/) and [seq](/functions/seq/) functions.

View file

@ -0,0 +1,25 @@
---
title: singularize
# linktitle: singularize
description: Converts a word according to a set of common English singularization rules.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings,singular]
signature: ["singularize INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
`{{ "cats" | singularize }}` → "cat"
See also the `.Data.Singular` [taxonomy variable](/variables/taxonomy/) for singularizing taxonomy names.

View file

@ -0,0 +1,32 @@
---
title: slice
# linktitle: slice
description: Creates a slice (array) of all passed arguments.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [slice, array, interface]
signature: ["slice ITEM..."]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
draft: false
aliases: []
toc: false
---
One use case is the concatenation of elements in combination with the [`delimit` function][]:
{{< code file="slice.html" >}}
{{ delimit (slice "foo" "bar" "buzz") ", " }}
<!-- returns the string "foo, bar, buzz" -->
{{< /code >}}
[`delimit` function]: /functions/delimit/

View file

@ -0,0 +1,27 @@
---
title: slicestr
# linktitle:
description: Creates a slice of a half-open range, including start and end indices.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings]
signature: ["slicestr STRING START [END]"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
For example, 1 and 4 creates a slice including elements 1 through 3.
The `end` index can be omitted; it defaults to the string's length.
* `{{slicestr "BatMan" 3}}` → "Man"
* `{{slicestr "BatMan" 0 3}}` → "Bat"

View file

@ -0,0 +1,65 @@
---
title: sort
# linktitle: sort
description: Sorts maps, arrays, and slices and returns a sorted slice.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [ordering,sorting,lists]
signature: []
workson: [lists,taxonomies,terms,groups]
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
A sorted array of map values will be returned with the keys eliminated. There are two optional arguments: `sortByField` and `sortAsc`. If left blank, sort will sort by keys (for maps) in ascending order as its default behavior.
```
+++
#tags: [ "tag3", "tag1", "tag2" ]
+++
// Site config
+++
[params.authors]
[params.authors.Derek]
"firstName" = "Derek"
"lastName" = "Perkins"
[params.authors.Joe]
"firstName" = "Joe"
"lastName" = "Bergevin"
[params.authors.Tanner]
"firstName" = "Tanner"
"lastName" = "Linsley"
+++
```
```
// Use default sort options - sort by key / ascending
Tags: {{ range sort .Params.tags }}{{ . }} {{ end }}
→ Outputs Tags: tag1 tag2 tag3
// Sort by value / descending
Tags: {{ range sort .Params.tags "value" "desc" }}{{ . }} {{ end }}
→ Outputs Tags: tag3 tag2 tag1
// Use default sort options - sort by value / descending
Authors: {{ range sort .Site.Params.authors }}{{ .firstName }} {{ end }}
→ Outputs Authors: Derek Joe Tanner
// Use default sort options - sort by value / descending
Authors: {{ range sort .Site.Params.authors "lastName" "desc" }}{{ .lastName }} {{ end }}
→ Outputs Authors: Perkins Linsley Bergevin
```

View file

@ -0,0 +1,24 @@
---
title: split
# linktitle: split
description: splits a string into substrings separated by a delimiter
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings]
signature: ["split STRING DELIM"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
* `{{split "tag1,tag2,tag3" "," }}` → ["tag1" "tag2" "tag3"]

View file

@ -0,0 +1,23 @@
---
title: string
# linktitle: string
description: Creates a string from the argument passed to the function
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings]
signature: ["string INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
* `{{string "BatMan"}}` → "BatMan"

View file

@ -0,0 +1,31 @@
---
title: substr
# linktitle:
description: Extracts parts of a string from a specified character's position and returns the specified number of characters.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings]
aliases: []
signature: ["substr STRING START [LENGTH]"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
---
It normally takes two parameters: `start` and `length`. It can also take one parameter: `start`, i.e. `length` is omitted, in which case the substring starting from start until the end of the string will be returned.
To extract characters from the end of the string, use a negative start number.
In addition, borrowing from the extended behavior described at http://php.net substr, if `length` is given and is negative, that number of characters will be omitted from the end of string.
```
{{substr "BatMan" 0 -3}} → "Bat"
{{substr "BatMan" 3 3}} → "Man"
```

View file

@ -0,0 +1,48 @@
---
title: time
linktitle:
description: Converts a timestamp string into a `time.Time` structure.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [dates,time]
signature: ["time INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
`time` converts a timestamp string into a [`time.Time`](https://godoc.org/time#Time) structure so you can access its fields:
```
{{ time "2016-05-28" }} → "2016-05-28T00:00:00Z"
{{ (time "2016-05-28").YearDay }} → 149
{{ mul 1000 (time "2016-05-28T10:30:00.00+10:00").Unix }} → 1464395400000, or Unix time in milliseconds
```
## Example: Using `time` to get Month Index
The following example takes a UNIX timestamp---set as `utimestamp: "1489276800"` in a content's front matter---converts the timestamp (string) to an integer using the [`int` function][int], and then uses [`printf`][] to convert the `Month` property of `time` into an index.
The following example may be useful when setting up [multilingual sites][multilingual]:
{{< code file="unix-to-month-integer.html" >}}
{{$time := time (int .Params.addDate)}}
=> $time = 1489276800
{{$time.Month}}
=> "March"
{{$monthindex := printf "%d" $time.Month }}
=> $monthindex = 3
{{< /code >}}
[int]: /functions/int/
[multilingual]: /content-management/multilingual/
[`printf`]: /functions/printf/

View file

@ -0,0 +1,33 @@
---
title: title
# linktitle:
description: Converts all characters in the provided string to title case.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions,fundamentals]
menu:
docs:
parent: "functions"
#tags: [strings]
signature: ["title INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
---
```
{{title "BatMan"}}` → "Batman"
```
Can be combined in pipes. In the following snippet, the link text is cleaned up using `humanize` to remove dashes and `title` to convert the value of `$name` to Intial Caps.
```
{{ range $name, $items := .Site.Taxonomies.categories }}
<li><a href="{{ printf "%s/%s" "categories" ($name | urlize | lower) | absURL }}">{{ $name | humanize | title }} ({{ len $items }})</a></li>
{{ end }}
```

View file

@ -0,0 +1,42 @@
---
title: trim
# linktitle:
description: Returns a slice of a passed string with all leading and trailing characters from cutset removed.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings]
signature: ["trim INPUT CUTSET"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
---
```
{{ trim "++Batman--" "+-" }} → "Batman"
```
`trim` *requires* the second argument, which tells the function specifically what to remove from the first argument. There is no default value for the second argument, so **the following usage will not work**:
```
{{ trim .Inner}}
```
Instead, the following example tells `trim` to remove extra new lines from the content contained in the [shortcode `.Inner` variable][shortcodevars]:
```
{{ trim .Inner "\n" }}
```
{{% note %}}
Go templates also provide a simple [method for trimming whitespace](/templates/introduction/#whitespace) from either side of a Go tag by including a hyphen (`-`).
{{% /note %}}
[shortcodevars]: /variables/shortcodes/

View file

@ -0,0 +1,29 @@
---
title: truncate
# linktitle: truncate
description: Truncates a text to a max length without cutting words or leaving unclosed HTML tags.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [strings]
signature: ["truncate SIZE INPUT", "truncate SIZE ELLIPSIS INPUT"]
workson: []
hugoversion: 19
relatedfuncs: []
deprecated: false
---
Since Go templates are HTML-aware, `truncate` will intelligently handle normal strings vs HTML strings:
```
{{ "<em>Keep my HTML</em>" | safeHTML | truncate 10 }}` → <em>Keep my …</em>`
```
{{% note %}}
If you have a raw string that contains HTML tags you want to remain treated as HTML, you will need to convert the string to HTML using the [`safeHTML` template function](/functions/safehtml) before sending the value to truncate. Otherwise, the HTML tags will be escaped when passed through the `truncate` function.
{{% /note %}}

View file

@ -0,0 +1,49 @@
---
title: union
# linktitle: union
description: Given two arrays or slices, returns a new array that contains the elements or objects that belong to either or both arrays/slices.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-03-12
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [filtering,lists]
signature: ["union SET1 SET2"]
workson: []
hugoversion: 0.20
relatedfuncs: [intersect,where]
deprecated: false
aliases: []
---
Given two arrays (or slices) A and B, this function will return a new array that contains the elements or objects that belong to either A or to B or to both. The elements supported are strings, integers, and floats (only float64).
```
{{ union (slice 1 2 3) (slice 3 4 5) }}
<!-- returns [1 2 3 4 5] -->
{{ union (slice 1 2 3) nil }}
<!-- returns [1 2 3] -->
{{ union nil (slice 1 2 3) }}
<!-- returns [1 2 3] -->
{{ union nil nil }}
<!-- returns an error because both arrays/slices have to be of the same type -->
```
This is also very useful to use as `OR` filters when combined with where:
```
{{ $pages := where .Site.RegularPages "Type" "not in" (slice "page" "about") }}
{{ $pages := $pages | union (where .Site.RegularPages "Params.pinned" true) }}
{{ $pages := $pages | intersect (where .Site.RegularPages "Params.images" "!=" nil) }}
```
The above fetches regular pages not of `page` or `about` type unless they are pinned. And finally, we exclude all pages with no `images` set in Page params.
See [intersect](/functions/intersect) for `AND`.

View file

@ -0,0 +1,31 @@
---
title: uniq
linktitle: uniq
description: Takes in a slice or array and returns a slice with subsequent duplicate elements removed.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [multilingual,i18n,urls]
signature: ["uniq SET"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
aliases: []
needsexamples: false
---
```
{{ uniq (slice 1 2 3 2) }}
{{ slice 1 2 3 2 | uniq }}
<!-- both return [1 2 3] -->
```

View file

@ -0,0 +1,38 @@
---
title: .Unix
draft: false
description: .Unix returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC.
godocref: https://golang.org/search?q=Unix#Functions
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
#tags: [dates,time]
categories: [functions]
menu:
docs:
parent: "functions"
signature: [".Unix"]
workson: [times]
hugoversion:
relatedfuncs: [Format,dateFormat,now,time]
deprecated: false
aliases: []
---
## Example: Time Passed Since Last Modification
This very simple one-liner uses `now.Unix` to calculate the amount of time that has passed between the `.LastMod` for the current page and the last build of the current page.
{{< code file="time-passed.html" >}}
{{ div (sub now.Unix .Lastmod.Unix) 86400 }}
{{< /code >}}
Since both values are integers, they can be subtracted and then divided by the number of seconds in a day (i.e., `60 * 60 * 24 == 86400`).
{{% note %}}
Hugo's output is *static*. For the example above to be realistic, the site needs to be built every day.
{{% /note %}}
[partial template]: /templates/partials/

View file

@ -0,0 +1,30 @@
---
title: upper
# linktitle: upper
description: Converts all characters in a string to uppercase
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
#tags: []
categories: [functions]
menu:
docs:
parent: "functions"
toc:
signature: ["upper INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
draft: false
aliases: []
---
Note that `upper` can be applied in your templates in more than one way:
```
{{ upper "BatMan" }} → "BATMAN"
{{ "BatMan" | upper }} → "BATMAN"
```

View file

@ -0,0 +1,73 @@
---
title: urlize
# linktitle: urlize
description: Takes a string, sanitizes it for usage in URLs, and converts spaces to hyphens.
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [urls,strings]
godocref:
signature: ["urlize INPUT"]
hugoversion:
deprecated: false
workson: []
relatedfuncs: []
---
The following examples pull from a content file with the following front matter:
{{< code file="content/blog/greatest-city.md" copy="false">}}
+++
title = "The World's Greatest City"
location = "Chicago IL"
tags = ["pizza","beer","hot dogs"]
+++
{{< /code >}}
The following might be used as a partial within a [single page template][singletemplate]:
{{< code file="layouts/partials/content-header.html" download="content-header.html" >}}
<header>
<h1>{{.Title}}</h1>
{{ with .Params.location }}
<div><a href="/locations/{{ . | urlize}}">{{.}}</a></div>
{{ end }}
<!-- Creates a list of tags for the content and links to each of their pages -->
{{ with .Params.tags }}
<ul>
{{range .}}
<li>
<a href="/tags/{{ . | urlize }}">{{ . }}</a>
</li>
{{end}}
</ul>
{{ end }}
</header>
{{< /code >}}
The preceding partial would then output to the rendered page as follows, assuming the page is being built with Hugo's default pretty URLs.
{{< output file="/blog/greatest-city/index.html" >}}
<header>
<h1>The World's Greatest City</h1>
<div><a href="/locations/chicago-il/">Chicago IL</a></div>
<ul>
<li>
<a href="/tags/pizza">pizza</a>
</li>
<li>
<a href="/tags/beer">beer</a>
</li>
<li>
<a href="/tags/hot-dogs">hot dogs</a>
</li>
</ul>
</header>
{{< /output >}}
[singletemplate]: /templates/single-page-templates/

View file

@ -0,0 +1,137 @@
---
title: where
# linktitle: where
description: Filters an array to only the elements containing a matching value for a given field.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
docs:
parent: "functions"
#tags: [filtering]
signature: ["where COLLECTION KEY [OPERATOR] MATCH"]
workson: [lists,taxonomies,terms,groups]
hugoversion:
relatedfuncs: [intersect,first,after,last]
deprecated: false
toc: true
needsexample: true
---
`where` filters an array to only the elements containing a matching value for a given field.
```
{{ range where .Data.Pages "Section" "post" }}
{{ .Content }}
{{ end }}
```
It can be used by dot-chaining the second argument to refer to a nested element of a value.
```
+++
series: golang
+++
```
```
{{ range where .Site.Pages "Params.series" "golang" }}
{{ .Content }}
{{ end }}
```
It can also be used with the logical operators `!=`, `>=`, `in`, etc. Without an operator, `where` compares a given field with a matching value equivalent to `=`.
```
{{ range where .Data.Pages "Section" "!=" "post" }}
{{ .Content }}
{{ end }}
```
The following logical operators are vailable with `where`:
`=`, `==`, `eq`
: `true` if a given field value equals a matching value
`!=`, `<>`, `ne`
: `true` if a given field value doesn't equal a matching value
`>=`, `ge`
: `true` if a given field value is greater than or equal to a matching value
`>`, `gt`
: `true` if a given field value is greater than a matching value
`<=`, `le`
: `true` if a given field value is lesser than or equal to a matching value
`<`, `lt`
: `true` if a given field value is lesser than a matching value
`in`
: `true` if a given field value is included in a matching value; a matching value must be an array or a slice
`not in`
: `true` if a given field value isn't included in a matching value; a matching value must be an array or a slice
`intersect`
: `true` if a given field value that is a slice/array of strings or integers contains elements in common with the matching value; it follows the same rules as the [`intersect` function][intersect].
## Use `where` with `intersect`
```
{{ range where .Site.Pages ".Params.tags" "intersect" .Params.tags }}
{{ if ne .Permalink $.Permalink }}
{{ .Render "summary" }}
{{ end }}
{{ end }}
```
You can also put the returned value of the `where` clauses into a variable:
{{< code file="where-intersect-variables.html" >}}
{{ $v1 := where .Site.Pages "Params.a" "v1" }}
{{ $v2 := where .Site.Pages "Params.b" "v2" }}
{{ $filtered := $v1 | intersect $v2 }}
{{ range $filtered }}
{{ end }}
{{< /code >}}
## Use `where` with `first`
The following grabs the first five content files in `post` using the [default ordering](/templates/lists/) for lists (i.e., `weight => date`):
{{< code file="where-with-first.html" >}}
{{ range first 5 (where .Data.Pages "Section" "post") }}
{{ .Content }}
{{ end }}
{{< /code >}}
## Nest `where` Clauses
You can also nest `where` clauses to drill down on lists of content by more than one parameter. The following first grabs all pages in the "blog" section and then ranges through the result of the first `where` clause and finds all pages that are *not* featured:
```
{{ range where (where .Data.Pages "Section" "blog" ) ".Params.featured" "!=" "true" }}
```
## Unset Fields
Filtering only works for set fields. To check whether a field is set or exists, you can use the operand `nil`.
This can be useful to filter a small amount of pages from a large pool. Instead of set field on all pages, you can set field on required pages only.
Only the following operators are available for `nil`
* `=`, `==`, `eq`: True if the given field is not set.
* `!=`, `<>`, `ne`: True if the given field is set.
```
{{ range where .Data.Pages ".Params.specialpost" "!=" nil }}
{{ .Content }}
{{ end }}
```
[intersect]: /functions/intersect/

View file

@ -0,0 +1,31 @@
---
title: with
# linktitle: with
description: Rebinds the context (`.`) within its scope and skips the block if the variable is absent.
godocref:
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-03-12
categories: [functions,fundamentals]
menu:
docs:
parent: "functions"
#tags: [conditionals]
signature: ["with INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
---
An alternative way of writing an `if` statement and then referencing the same value is to use `with` instead. `with` rebinds the context (`.`) within its scope and skips the block if the variable is absent or unset.
The following example checks for a [user-defined site variable](/variables/site/) called `twitteruser`. If the key-value is not set, the following will render nothing:
{{< code file="layouts/partials/twitter.html" >}}
{{with .Site.Params.twitteruser}}<span class="twitter">
<a href="https://twitter.com/{{.}}" rel="author">
<img src="/images/twitter.png" width="48" height="48" title="Twitter: {{.}}"
alt="Twitter"></a>
</span>{{end}}
{{< /code >}}