Source code for website arcusiridis.com
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

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