Debian Codegraph @

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

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