len.md (2059B)
1 --- 2 title: len 3 linktitle: len 4 description: Returns the length of a variable according to its type. 5 date: 2017-02-01 6 publishdate: 2017-02-01 7 lastmod: 2017-04-18 8 categories: [functions] 9 menu: 10 docs: 11 parent: "functions" 12 keywords: [] 13 signature: ["len INPUT"] 14 workson: [lists,taxonomies,terms] 15 hugoversion: 16 relatedfuncs: [] 17 deprecated: false 18 toc: false 19 aliases: [] 20 --- 21 22 `len` is a built-in function in Go that returns the length of a variable according to its type. From the Go documentation: 23 24 > Array: the number of elements in v. 25 > 26 > Pointer to array: the number of elements in *v (even if v is nil). 27 > 28 > Slice, or map: the number of elements in v; if v is nil, len(v) is zero. 29 > 30 > String: the number of bytes in v. 31 > 32 > Channel: the number of elements queued (unread) in the channel buffer; if v is nil, len(v) is zero. 33 34 `len` is also considered a [fundamental function for Hugo templating][]. 35 36 ## `len` Example 1: Longer Headings 37 38 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>`: 39 40 {{< code file="check-title-length.html" >}} 41 <header> 42 <h1{{if gt (len .Title) 80}} class="long-title"{{end}}>{{.Title}}</h1> 43 </header> 44 {{< /code >}} 45 46 ## `len` Example 2: Counting Pages with `where` 47 48 The following templating uses [`where`][] in conjunction with `len` to 49 figure out the total number of content pages in a `posts` [section][]: 50 51 {{< code file="how-many-posts.html" >}} 52 {{ $posts := (where .Site.RegularPages "Section" "==" "posts") }} 53 {{ $postCount := len $posts }} 54 {{< /code >}} 55 56 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][]. 57 58 59 [fundamental function for Hugo templating]: /templates/introduction/ 60 [list templates]: /templates/lists/ 61 [section]: /content-management/sections/ 62 [site variable]: /variables/site/ 63 [`where`]: /functions/where/