Debian Codegraph @

tpl/partials/partials.go

raw
1 // Copyright 2017 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package partials provides template functions for working with reusable
15 // templates.
16 package partials
17
18 import (
19 "context"
20 "errors"
21 "fmt"
22 "html/template"
23 "strings"
24 "time"
25
26 "github.com/bep/lazycache"
27 "github.com/gohugoio/hugo/common/constants"
28 "github.com/gohugoio/hugo/common/hashing"
29 "github.com/gohugoio/hugo/identity"
30 texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate"
31
32 "github.com/gohugoio/hugo/tpl"
33 "github.com/gohugoio/hugo/tpl/tplimpl"
34
35 bp "github.com/gohugoio/hugo/bufferpool"
36 "github.com/gohugoio/hugo/deps"
37 )
38
39 type partialCacheKey struct {
40 Name string
41 Variants []any
42 }
43 type includeResult struct {
44 name string
45 result any
46 mangager identity.Manager
47 err error
48 }
49
50 func (k partialCacheKey) Key() string {
51 if k.Variants == nil {
52 return k.Name
53 }
54 return hashing.HashString(append([]any{k.Name}, k.Variants...)...)
55 }
56
57 // partialCache represents a LRU cache of partials.
58 type partialCache struct {
59 cache *lazycache.Cache[string, includeResult]
60 }
61
62 func (p *partialCache) clear() {
63 p.cache.DeleteFunc(func(s string, r includeResult) bool {
64 return true
65 })
66 }
67
68 // New returns a new instance of the templates-namespaced template functions.
69 func New(deps *deps.Deps) *Namespace {
70 // This lazycache was introduced in Hugo 0.111.0.
71 // We're going to expand and consolidate all memory caches in Hugo using this,
72 // so just set a high limit for now.
73 lru := lazycache.New(lazycache.Options[string, includeResult]{MaxEntries: 1000})
74
75 cache := &partialCache{cache: lru}
76 deps.BuildStartListeners.Add(
77 func(...any) bool {
78 cache.clear()
79 return false
80 },
81 )
82
83 return &Namespace{
84 deps: deps,
85 cachedPartials: cache,
86 }
87 }
88
89 // Namespace provides template functions for the "templates" namespace.
90 type Namespace struct {
91 deps *deps.Deps
92 cachedPartials *partialCache
93 }
94
95 // Include executes the named partial.
96 // If the partial contains a return statement, that value will be returned.
97 // Else, the rendered output will be returned:
98 // A string if the partial is a text/template, or template.HTML when html/template.
99 // Note that ctx is provided by Hugo, not the end user.
100 func (ns *Namespace) Include(ctx context.Context, name string, contextList ...any) (any, error) {
101 res := ns.include(ctx, name, contextList...)
102 if res.err != nil {
103 return nil, res.err
104 }
105
106 if ns.deps.Metrics != nil {
107 ns.deps.Metrics.TrackValue(res.name, res.result, false)
108 }
109
110 return res.result, nil
111 }
112
113 func (ns *Namespace) include(ctx context.Context, name string, dataList ...any) includeResult {
114 name, err := ns.deps.TemplateStore.ResolvePartialName(ctx, name)
115 if err != nil {
116 return includeResult{err: err}
117 }
118 v, err := ns.lookup(name)
119 if err != nil {
120 return includeResult{err: err}
121 }
122 return ns.doInclude(ctx, "", v, dataList...)
123 }
124
125 func (ns *Namespace) lookup(name string) (*tplimpl.TemplInfo, error) {
126 if strings.HasPrefix(name, "partials/") {
127 // This is most likely not what the user intended.
128 // This worked before Hugo 0.146.0.
129 ns.deps.Log.Warnidf(constants.WarnPartialSuperfluousPrefix, "Doubtful use of partial function in {{ partial \"%s\"}}), this is most likely not what you want. Consider removing superfluous prefix \"partials/\" from template name given as first function argument.", name)
130 }
131 v := ns.deps.TemplateStore.LookupPartial(name)
132 if v == nil {
133 return nil, fmt.Errorf("partial %q not found", name)
134 }
135 return v, nil
136 }
137
138 // include is a helper function that lookups and executes the named partial.
139 // Returns the final template name and the rendered output.
140 func (ns *Namespace) doInclude(ctx context.Context, key string, templ *tplimpl.TemplInfo, dataList ...any) includeResult {
141 if templ.ParseInfo.HasPartialInner {
142 stack := tpl.Context.PartialDecoratorIDStack.Get(ctx)
143 if stack != nil {
144 if id, ok := stack.Peek(); ok {
145 // Signal that inner exists.
146 id.Bool = true
147 }
148 }
149 }
150 var data any
151 if len(dataList) > 0 {
152 data = dataList[0]
153 }
154
155 b := bp.GetBuffer()
156 defer bp.PutBuffer(b)
157
158 if err := ns.deps.GetTemplateStore().ExecuteWithContextAndKey(ctx, key, templ, b, data); err != nil {
159 var rerr *texttemplate.ReturnError
160 if !errors.As(err, &rerr) {
161 return includeResult{err: err}
162 }
163 // The partial has a {{ return <value> }}; any rendered output is discarded.
164 return includeResult{
165 name: templ.Name(),
166 result: rerr.Value,
167 }
168 }
169
170 var result any
171
172 if _, ok := templ.Template.(*texttemplate.Template); ok {
173 result = b.String()
174 } else {
175 result = template.HTML(b.String())
176 }
177
178 return includeResult{
179 name: templ.Name(),
180 result: result,
181 }
182 }
183
184 // IncludeCached executes and caches partial templates. The cache is created with name+variants as the key.
185 // Note that ctx is provided by Hugo, not the end user.
186 func (ns *Namespace) IncludeCached(ctx context.Context, name string, context any, variants ...any) (any, error) {
187 start := time.Now()
188 name, err := ns.deps.TemplateStore.ResolvePartialName(ctx, name)
189 if err != nil {
190 return nil, err
191 }
192 keyString := name
193 if len(variants) > 0 {
194 key := partialCacheKey{
195 Name: name,
196 Variants: variants,
197 }
198 keyString = key.Key()
199 }
200
201 depsManagerIn := tpl.Context.GetDependencyManagerInCurrentScope(ctx)
202 ti, err := ns.lookup(name)
203 if err != nil {
204 return nil, err
205 }
206
207 if parent := tpl.Context.CurrentTemplate.Get(ctx); parent != nil {
208 for parent != nil {
209 if parent.CurrentTemplateInfoOps == ti && parent.Key == keyString {
210 // This will deadlock if we continue.
211 return nil, fmt.Errorf("circular call stack detected in partial %q", ti.Filename())
212 }
213 parent = parent.Parent
214 }
215 }
216
217 r, found, err := ns.cachedPartials.cache.GetOrCreate(keyString, func(string) (includeResult, error) {
218 var depsManagerShared identity.Manager
219 if ns.deps.Conf.Watching() {
220 // We need to create a shared dependency manager to pass downwards
221 // and add those same dependencies to any cached invocation of this partial.
222 depsManagerShared = identity.NewManager()
223 ctx = tpl.Context.DependencyManagerScopedProvider.Set(ctx, depsManagerShared.(identity.DependencyManagerScopedProvider))
224 }
225 // Mark the ctx so templates.Defer can reject being called from a cached body.
226 ctx = tpl.Context.IsInPartialCached.Set(ctx, true)
227 r := ns.doInclude(ctx, keyString, ti, context)
228 if ns.deps.Conf.Watching() {
229 r.mangager = depsManagerShared
230 }
231 return r, r.err
232 })
233 if err != nil {
234 return nil, err
235 }
236
237 if ns.deps.Metrics != nil {
238 if found {
239 // The templates that gets executed is measured in Execute.
240 // We need to track the time spent in the cache to
241 // get the totals correct.
242 ns.deps.Metrics.MeasureSince(r.name, start)
243 }
244 ns.deps.Metrics.TrackValue(r.name, r.result, found)
245 }
246
247 if r.mangager != nil && depsManagerIn != nil {
248 depsManagerIn.AddIdentity(r.mangager)
249 }
250
251 return r.result, nil
252 }