You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

344 lines
9.6 KiB

  1. +++
  2. title = "(Hu)go Template Primer"
  3. description = ""
  4. tags = [
  5. "go",
  6. "golang",
  7. "templates",
  8. "themes",
  9. "development",
  10. ]
  11. date = "2014-04-02"
  12. categories = [
  13. "Development",
  14. "golang",
  15. ]
  16. menu = "main"
  17. +++
  18. Hugo uses the excellent [go][] [html/template][gohtmltemplate] library for
  19. its template engine. It is an extremely lightweight engine that provides a very
  20. small amount of logic. In our experience that it is just the right amount of
  21. logic to be able to create a good static website. If you have used other
  22. template systems from different languages or frameworks you will find a lot of
  23. similarities in go templates.
  24. This document is a brief primer on using go templates. The [go docs][gohtmltemplate]
  25. provide more details.
  26. ## Introduction to Go Templates
  27. Go templates provide an extremely simple template language. It adheres to the
  28. belief that only the most basic of logic belongs in the template or view layer.
  29. One consequence of this simplicity is that go templates parse very quickly.
  30. A unique characteristic of go templates is they are content aware. Variables and
  31. content will be sanitized depending on the context of where they are used. More
  32. details can be found in the [go docs][gohtmltemplate].
  33. ## Basic Syntax
  34. Go lang templates are html files with the addition of variables and
  35. functions.
  36. **Go variables and functions are accessible within {{ }}**
  37. Accessing a predefined variable "foo":
  38. {{ foo }}
  39. **Parameters are separated using spaces**
  40. Calling the add function with input of 1, 2:
  41. {{ add 1 2 }}
  42. **Methods and fields are accessed via dot notation**
  43. Accessing the Page Parameter "bar"
  44. {{ .Params.bar }}
  45. **Parentheses can be used to group items together**
  46. {{ if or (isset .Params "alt") (isset .Params "caption") }} Caption {{ end }}
  47. ## Variables
  48. Each go template has a struct (object) made available to it. In hugo each
  49. template is passed either a page or a node struct depending on which type of
  50. page you are rendering. More details are available on the
  51. [variables](/layout/variables) page.
  52. A variable is accessed by referencing the variable name.
  53. <title>{{ .Title }}</title>
  54. Variables can also be defined and referenced.
  55. {{ $address := "123 Main St."}}
  56. {{ $address }}
  57. ## Functions
  58. Go template ship with a few functions which provide basic functionality. The go
  59. template system also provides a mechanism for applications to extend the
  60. available functions with their own. [Hugo template
  61. functions](/layout/functions) provide some additional functionality we believe
  62. are useful for building websites. Functions are called by using their name
  63. followed by the required parameters separated by spaces. Template
  64. functions cannot be added without recompiling hugo.
  65. **Example:**
  66. {{ add 1 2 }}
  67. ## Includes
  68. When including another template you will pass to it the data it will be
  69. able to access. To pass along the current context please remember to
  70. include a trailing dot. The templates location will always be starting at
  71. the /layout/ directory within Hugo.
  72. **Example:**
  73. {{ template "chrome/header.html" . }}
  74. ## Logic
  75. Go templates provide the most basic iteration and conditional logic.
  76. ### Iteration
  77. Just like in go, the go templates make heavy use of range to iterate over
  78. a map, array or slice. The following are different examples of how to use
  79. range.
  80. **Example 1: Using Context**
  81. {{ range array }}
  82. {{ . }}
  83. {{ end }}
  84. **Example 2: Declaring value variable name**
  85. {{range $element := array}}
  86. {{ $element }}
  87. {{ end }}
  88. **Example 2: Declaring key and value variable name**
  89. {{range $index, $element := array}}
  90. {{ $index }}
  91. {{ $element }}
  92. {{ end }}
  93. ### Conditionals
  94. If, else, with, or, & and provide the framework for handling conditional
  95. logic in Go Templates. Like range, each statement is closed with `end`.
  96. Go Templates treat the following values as false:
  97. * false
  98. * 0
  99. * any array, slice, map, or string of length zero
  100. **Example 1: If**
  101. {{ if isset .Params "title" }}<h4>{{ index .Params "title" }}</h4>{{ end }}
  102. **Example 2: If -> Else**
  103. {{ if isset .Params "alt" }}
  104. {{ index .Params "alt" }}
  105. {{else}}
  106. {{ index .Params "caption" }}
  107. {{ end }}
  108. **Example 3: And & Or**
  109. {{ if and (or (isset .Params "title") (isset .Params "caption")) (isset .Params "attr")}}
  110. **Example 4: With**
  111. An alternative way of writing "if" and then referencing the same value
  112. is to use "with" instead. With rebinds the context `.` within its scope,
  113. and skips the block if the variable is absent.
  114. The first example above could be simplified as:
  115. {{ with .Params.title }}<h4>{{ . }}</h4>{{ end }}
  116. **Example 5: If -> Else If**
  117. {{ if isset .Params "alt" }}
  118. {{ index .Params "alt" }}
  119. {{ else if isset .Params "caption" }}
  120. {{ index .Params "caption" }}
  121. {{ end }}
  122. ## Pipes
  123. One of the most powerful components of go templates is the ability to
  124. stack actions one after another. This is done by using pipes. Borrowed
  125. from unix pipes, the concept is simple, each pipeline's output becomes the
  126. input of the following pipe.
  127. Because of the very simple syntax of go templates, the pipe is essential
  128. to being able to chain together function calls. One limitation of the
  129. pipes is that they only can work with a single value and that value
  130. becomes the last parameter of the next pipeline.
  131. A few simple examples should help convey how to use the pipe.
  132. **Example 1 :**
  133. {{ if eq 1 1 }} Same {{ end }}
  134. is the same as
  135. {{ eq 1 1 | if }} Same {{ end }}
  136. It does look odd to place the if at the end, but it does provide a good
  137. illustration of how to use the pipes.
  138. **Example 2 :**
  139. {{ index .Params "disqus_url" | html }}
  140. Access the page parameter called "disqus_url" and escape the HTML.
  141. **Example 3 :**
  142. {{ if or (or (isset .Params "title") (isset .Params "caption")) (isset .Params "attr")}}
  143. Stuff Here
  144. {{ end }}
  145. Could be rewritten as
  146. {{ isset .Params "caption" | or isset .Params "title" | or isset .Params "attr" | if }}
  147. Stuff Here
  148. {{ end }}
  149. ## Context (aka. the dot)
  150. The most easily overlooked concept to understand about go templates is that {{ . }}
  151. always refers to the current context. In the top level of your template this
  152. will be the data set made available to it. Inside of a iteration it will have
  153. the value of the current item. When inside of a loop the context has changed. .
  154. will no longer refer to the data available to the entire page. If you need to
  155. access this from within the loop you will likely want to set it to a variable
  156. instead of depending on the context.
  157. **Example:**
  158. {{ $title := .Site.Title }}
  159. {{ range .Params.tags }}
  160. <li> <a href="{{ $baseurl }}/tags/{{ . | urlize }}">{{ . }}</a> - {{ $title }} </li>
  161. {{ end }}
  162. Notice how once we have entered the loop the value of {{ . }} has changed. We
  163. have defined a variable outside of the loop so we have access to it from within
  164. the loop.
  165. # Hugo Parameters
  166. Hugo provides the option of passing values to the template language
  167. through the site configuration (for sitewide values), or through the meta
  168. data of each specific piece of content. You can define any values of any
  169. type (supported by your front matter/config format) and use them however
  170. you want to inside of your templates.
  171. ## Using Content (page) Parameters
  172. In each piece of content you can provide variables to be used by the
  173. templates. This happens in the [front matter](/content/front-matter).
  174. An example of this is used in this documentation site. Most of the pages
  175. benefit from having the table of contents provided. Sometimes the TOC just
  176. doesn't make a lot of sense. We've defined a variable in our front matter
  177. of some pages to turn off the TOC from being displayed.
  178. Here is the example front matter:
  179. ```
  180. ---
  181. title: "Permalinks"
  182. date: "2013-11-18"
  183. aliases:
  184. - "/doc/permalinks/"
  185. groups: ["extras"]
  186. groups_weight: 30
  187. notoc: true
  188. ---
  189. ```
  190. Here is the corresponding code inside of the template:
  191. {{ if not .Params.notoc }}
  192. <div id="toc" class="well col-md-4 col-sm-6">
  193. {{ .TableOfContents }}
  194. </div>
  195. {{ end }}
  196. ## Using Site (config) Parameters
  197. In your top-level configuration file (eg, `config.yaml`) you can define site
  198. parameters, which are values which will be available to you in chrome.
  199. For instance, you might declare:
  200. ```yaml
  201. params:
  202. CopyrightHTML: "Copyright &#xA9; 2013 John Doe. All Rights Reserved."
  203. TwitterUser: "spf13"
  204. SidebarRecentLimit: 5
  205. ```
  206. Within a footer layout, you might then declare a `<footer>` which is only
  207. provided if the `CopyrightHTML` parameter is provided, and if it is given,
  208. you would declare it to be HTML-safe, so that the HTML entity is not escaped
  209. again. This would let you easily update just your top-level config file each
  210. January 1st, instead of hunting through your templates.
  211. ```
  212. {{if .Site.Params.CopyrightHTML}}<footer>
  213. <div class="text-center">{{.Site.Params.CopyrightHTML | safeHtml}}</div>
  214. </footer>{{end}}
  215. ```
  216. An alternative way of writing the "if" and then referencing the same value
  217. is to use "with" instead. With rebinds the context `.` within its scope,
  218. and skips the block if the variable is absent:
  219. ```
  220. {{with .Site.Params.TwitterUser}}<span class="twitter">
  221. <a href="https://twitter.com/{{.}}" rel="author">
  222. <img src="/images/twitter.png" width="48" height="48" title="Twitter: {{.}}"
  223. alt="Twitter"></a>
  224. </span>{{end}}
  225. ```
  226. Finally, if you want to pull "magic constants" out of your layouts, you can do
  227. so, such as in this example:
  228. ```
  229. <nav class="recent">
  230. <h1>Recent Posts</h1>
  231. <ul>{{range first .Site.Params.SidebarRecentLimit .Site.Recent}}
  232. <li><a href="{{.RelPermalink}}">{{.Title}}</a></li>
  233. {{end}}</ul>
  234. </nav>
  235. ```
  236. [go]: <http://golang.org/>
  237. [gohtmltemplate]: <http://golang.org/pkg/html/template/>