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 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.
14
15 Hugo publishes the resource to the target path when you call its [`Publish`][], [`Permalink`][], or [`RelPermalink`][] methods.
16
17 Let's say you have a CSS file that you wish to populate with values from your project configuration:
18
19 ```go-html-template {file="assets/css/template.css"}
20 body {
21 background-color: {{ site.Params.style.bg_color }};
22 color: {{ site.Params.style.text_color }};
23 }
24 ```
25
26 And your project configuration contains:
27
28 {{< code-toggle file=hugo >}}
29 [params.style]
30 bg_color = '#fefefe'
31 text_color = '#222'
32 {{< /code-toggle >}}
33
34 Place this in your baseof.html template:
35
36 ```go-html-template
37 {{ with resources.Get "css/template.css" }}
38 {{ with resources.ExecuteAsTemplate "css/main.css" $ . }}
39 <link rel="stylesheet" href="{{ .RelPermalink }}">
40 {{ end }}
41 {{ end }}
42 ```
43
44 The example above:
45
46 1. Captures the template as a resource
47 1. Executes the resource as a template, passing the current page in context
48 1. Publishes the resource to css/main.css
49
50 The result is:
51
52 ```css {file="public/css/main.css"}
53 body {
54 background-color: #fefefe;
55 color: #222;
56 }
57 ```
58
59 [`Permalink`]: /methods/resource/permalink/
60 [`Publish`]: /methods/resource/publish/
61 [`RelPermalink`]: /methods/resource/relpermalink/