Content partials
This section describes content partials, which have go-html content only. For java-script and css partials check “JS and CSS partials” section.
Partial is a part of document that can be re-used in several pages, which may be convenient if application consists of several pages with same content in some places. Let’s say we have application where navigation content repeated in every page, with partial we can put this content in one template and re-use it in every page. Sounds very convenient, but still they have some restrictions:
- Partials can also contain unlimited partials, but the maximum depth (nested levels) is currently limited to 5
- Partials cannot have js and css imports/blocks
Create partial
To create a partial, go to the template editor
and pick Create -> Create new template, then define name and select type Partial from the dropdown.
Editor will generate very simple initial code for the partial and append suffix -partial
to the
template name:
{{ define "my-cool-partial" }}
<!-- Feel free to write your awesome component using HTML and powerful templating options -->
{{ end }}
So lets update newly created partial with some content
{{ define "my-cool-partial" }}
<h1>Hello Goerp!</h1>
{{ end }}
and now let’s inject partial into the page:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
{{ template "my-cool-partial" . }}
</body>
</html>
Passing data to the partial
In the last section we created simple partial and injected into the page. There is dot in the end
of partial injection statement, which means that we are passing all data that was sent from back-end
with the response to the partial. In this case we can use any available variable field, for example
changing our <h1>Hello Goerp!</h1>
to the <h1>Hello Goerp! Client code {{ .Data.Session.ClientCode }}</h1>
will print the client code number.
However, in some cases we may want to pass specific set of variables instead of all available ones.
In this case we can use in-build function that will produce variable of the key-value pairs (check
Built-in helper functions topic mkMap
func for more details). So we need to update our partial to use the variable:
<h1>Hello Goerp! Client code {{ .clientCode }}</h1>
and then pass this variable while injecting
the template in our page: {{ template "my-cool-partial" mkMap "clientCode" 123456 }}
. Or we can
pass any part of available in page data, this will also work: {{ template "my-cool-partial" .Data.Session }}
and then <h1>Hello Goerp! Client code {{ .ClientCode }}; session key {{ .SessionKey }}</h1>