Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

goisforlovers.md 9.5KB

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