Debian Codegraph @

docs/content/en/functions/resources/ExecuteAsTemplate.md

raw
1 ---
2 title: resources.ExecuteAsTemplate
3 description: Returns a resource created from a Go template, parsed and executed with the given context.
4 categories: []
5 keywords: []
6 params:
7 functions_and_methods:
8 aliases: []
9 returnType: resource.Resource
10 signatures: [resources.ExecuteAsTemplate TARGETPATH CONTEXT RESOURCE]
11 ---
12
13 {{% include "/_common/methods/resource/global-page-remote-resources.md" %}}
14
15 The `resources.ExecuteAsTemplate` function returns a resource created from a Go template, parsed and executed with the given context, caching the result using the target path as its cache key.
16
17 Hugo publishes the resource to the target path when you call its [`Publish`][], [`Permalink`][], or [`RelPermalink`][] methods.
18
19 Let's say you have a CSS file that you wish to populate with values from your project configuration:
20
21 ```go-html-template {file="assets/css/template.css"}
22 body {
23 background-color: {{ site.Params.style.bg_color }};
24 color: {{ site.Params.style.text_color }};
25 }
26 ```
27
28 And your project configuration contains:
29
30 {{< code-toggle file=hugo >}}
31 [params.style]
32 bg_color = '#fefefe'
33 text_color = '#222'
34 {{< /code-toggle >}}
35
36 Place this in your baseof.html template:
37
38 ```go-html-template
39 {{ with resources.Get "css/template.css" }}
40 {{ with resources.ExecuteAsTemplate "css/main.css" $ . }}
41 <link rel="stylesheet" href="{{ .RelPermalink }}">
42 {{ end }}
43 {{ end }}
44 ```
45
46 The example above:
47
48 1. Captures the template as a resource
49 1. Executes the resource as a template, passing the current page in context
50 1. Publishes the resource to css/main.css
51
52 The result is:
53
54 ```css {file="public/css/main.css"}
55 body {
56 background-color: #fefefe;
57 color: #222;
58 }
59 ```
60
61 [`Permalink`]: /methods/resource/permalink/
62 [`Publish`]: /methods/resource/publish/
63 [`RelPermalink`]: /methods/resource/relpermalink/