Debian Codegraph @

docs/content/en/functions/templates/Defer.md

raw
1 ---
2 title: templates.Defer
3 description: Defers execution of a template until all sites and output formats have been rendered.
4 categories: []
5 keywords: []
6 params:
7 functions_and_methods:
8 aliases: []
9 returnType: string
10 signatures: [templates.Defer OPTIONS]
11 aliases: [/functions/templates.defer]
12 ---
13
14 ## Usage
15
16 The `templates.Defer` function defers the execution of a template until all sites and output formats have been rendered.
17
18 > [!NOTE]
19 > Do not call this function within a _partial_ template called with the `partialCached` function. This restriction applies transitively: if `partialCached` calls a _partial_ template that calls `templates.Defer`, Hugo returns an error. Using this function within shortcode or render hook templates may also lead to unpredictable results.
20
21 > [!NOTE]
22 > This function only works in combination with the `with` keyword.
23 >
24 > Variables defined on the outside are not visible on the inside and vice versa. To pass in data, use the `data` option.
25
26 The `templates.Defer` function requires a single argument, a map with the following optional keys:
27
28 `key`
29 : (`string`) The key to use for the deferred template. This will, combined with a hash of the template content, be used as a cache key. Without this key, Hugo executes the deferred template on every render, which is inefficient for shared resources like CSS and JavaScript.
30
31 `data`
32 : (`map`) Optional map to pass as data to the deferred template. This will be available in the deferred template as `.` or `$`.
33
34 ```go-html-template
35 Language Outside: {{ site.Language.Name }}
36 Page Outside: {{ .RelPermalink }}
37 I18n Outside: {{ i18n "hello" }}
38 {{ $data := (dict "page" . )}}
39 {{ with (templates.Defer (dict "data" $data )) }}
40 Language Inside: {{ site.Language.Name }}
41 Page Inside: {{ .page.RelPermalink }}
42 I18n Inside: {{ i18n "hello" }}
43 {{ end }}
44 ```
45
46 The [output format][], [site][], and [language][] will be the same, even if the execution is deferred. In the example above, this means that the `site.Language.Name` and `.RelPermalink` will be the same on the inside and the outside of the deferred template.
47
48 ## Examples
49
50 The following examples defer CSS processing until Hugo has finished rendering all pages.
51
52 ### Process Tailwind CSS
53
54 The [`css.TailwindCSS`][] function uses [`hugo_stats.json`][] to determine which classes and other HTML identifiers are in use. Because Hugo must finish rendering all pages before writing this file, use the following templates to defer the CSS processing:
55
56 ```go-html-template {file="layouts/baseof.html" copy=true}
57 <head>
58 {{ with (templates.Defer (dict "key" "global")) }}
59 {{ partial "css.html" . }}
60 {{ end }}
61 </head>
62 ```
63
64 ```go-html-template {file="layouts/_partials/css.html" copy=true}
65 {{ with resources.Get "css/main.css" }}
66 {{ $opts := dict "minify" (not hugo.IsDevelopment) }}
67 {{ with . | css.TailwindCSS $opts }}
68 {{ if hugo.IsDevelopment }}
69 <link rel="stylesheet" href="{{ .RelPermalink }}">
70 {{ else }}
71 {{ with . | fingerprint }}
72 <link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
73 {{ end }}
74 {{ end }}
75 {{ end }}
76 {{ end }}
77 ```
78
79 For the above to work well when running the server (or `hugo -w`), add the following configuration:
80
81 {{< code-toggle file=hugo >}}
82 [build]
83 [build.buildStats]
84 enable = true
85 [[build.cachebusters]]
86 source = 'assets/notwatching/hugo_stats\.json'
87 target = 'css'
88 [[build.cachebusters]]
89 source = '(postcss|tailwind)\.config\.js'
90 target = 'css'
91 [module]
92 [[module.mounts]]
93 source = 'assets'
94 target = 'assets'
95 [[module.mounts]]
96 disableWatch = true
97 source = 'hugo_stats.json'
98 target = 'assets/notwatching/hugo_stats.json'
99 {{< /code-toggle >}}
100
101 ### Remove unused CSS
102
103 The `postcss.config.mjs` configuration file created in [Step 4](#step-4) directs the [`PurgeCSS`][] plugin to read [`hugo_stats.json`][] when the [`css.PostCSS`][] function runs. Because Hugo only writes this file after all pages are rendered, the CSS processing must be deferred.
104
105 Step 1
106 : Install [Node.js][].
107
108 Step 2
109 : Install the required Node packages in the root of your project:
110
111 ```sh {copy=true}
112 npm i -D postcss postcss-cli autoprefixer @fullhuman/postcss-purgecss
113 ```
114
115 Step 3
116 : Enable creation of the [`hugo_stats.json`][] file when building the site. If you are only using this for the production build, consider placing it below [`config/production`][].
117
118 {{< code-toggle file=hugo copy=true >}}
119 [build.buildStats]
120 enable = true
121 {{< /code-toggle >}}
122
123 See the [configure build][] documentation for details and options.
124
125 Step 4
126 : Create a configuration file for the `PurgeCSS` and `autoprefixer` plugins in the root of your project.
127
128 ```js {file="postcss.config.mjs" copy=true}
129 import autoprefixer from 'autoprefixer';
130 import purgeCSSPlugin from '@fullhuman/postcss-purgecss';
131
132 const purgecss = purgeCSSPlugin({
133 content: ['./hugo_stats.json'],
134 defaultExtractor: content => {
135 const els = JSON.parse(content).htmlElements;
136 return [
137 ...(els.tags || []),
138 ...(els.classes || []),
139 ...(els.ids || []),
140 ];
141 },
142 // https://purgecss.com/safelisting.html
143 safelist: []
144 });
145
146 export default {
147 plugins: [
148 process.env.HUGO_ENVIRONMENT !== 'development' ? purgecss : null,
149 autoprefixer,
150 ]
151 };
152 ```
153
154 Step 5
155 : Place your CSS file within the `assets/css` directory.
156
157 Step 6
158 : Defer CSS processing so it runs after the site has been rendered:
159
160 ```go-html-template {file="layouts/baseof.html" copy=true}
161 <head>
162 {{ with (templates.Defer (dict "key" "global")) }}
163 {{ partial "css.html" . }}
164 {{ end }}
165 </head>
166 ```
167
168 ```go-html-template {file="layouts/_partials/css.html" copy=true}
169 {{ with resources.Get "css/main.css" }}
170 {{ if hugo.IsDevelopment }}
171 <link rel="stylesheet" href="{{ .RelPermalink }}">
172 {{ else }}
173 {{ with . | postCSS | minify | fingerprint }}
174 <link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
175 {{ end }}
176 {{ end }}
177 {{ end }}
178 ```
179
180 [Node.js]: https://nodejs.org/en
181 [`PurgeCSS`]: https://github.com/FullHuman/purgecss
182 [`config/production`]: /configuration/introduction/#configuration-directory
183 [`css.PostCSS`]: /functions/css/postcss/
184 [`css.TailwindCSS`]: /functions/css/tailwindcss/
185 [`hugo_stats.json`]: /configuration/build/
186 [configure build]: /configuration/build/
187 [language]: /methods/site/language/
188 [output format]: /configuration/output-formats/
189 [site]: /methods/page/site/