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 v, err := ns.lookup(name)
115 if err != nil {
116 return includeResult{err: err}
117 }
118 return ns.doInclude(ctx, "", v, dataList...)
119 }
120
121 func (ns *Namespace) lookup(name string) (*tplimpl.TemplInfo, error) {
122 if strings.HasPrefix(name, "partials/") {
123 // This is most likely not what the user intended.
124 // This worked before Hugo 0.146.0.
125 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)
126 }
127 v := ns.deps.TemplateStore.LookupPartial(name)
128 if v == nil {
129 return nil, fmt.Errorf("partial %q not found", name)
130 }
131 return v, nil
132 }
133
134 // include is a helper function that lookups and executes the named partial.
135 // Returns the final template name and the rendered output.
136 func (ns *Namespace) doInclude(ctx context.Context, key string, templ *tplimpl.TemplInfo, dataList ...any) includeResult {
137 if templ.ParseInfo.HasPartialInner {
138 stack := tpl.Context.PartialDecoratorIDStack.Get(ctx)
139 if stack != nil {
140 if id, ok := stack.Peek(); ok {
141 // Signal that inner exists.
142 id.Bool = true
143 }
144 }
145 }
146 var data any
147 if len(dataList) > 0 {
148 data = dataList[0]
149 }
150
151 b := bp.GetBuffer()
152 defer bp.PutBuffer(b)
153
154 if err := ns.deps.GetTemplateStore().ExecuteWithContextAndKey(ctx, key, templ, b, data); err != nil {
155 var rerr *texttemplate.ReturnError
156 if !errors.As(err, &rerr) {
157 return includeResult{err: err}
158 }
159 // The partial has a {{ return <value> }}; any rendered output is discarded.
160 return includeResult{
161 name: templ.Name(),
162 result: rerr.Value,
163 }
164 }
165
166 var result any
167
168 if _, ok := templ.Template.(*texttemplate.Template); ok {
169 result = b.String()
170 } else {
171 result = template.HTML(b.String())
172 }
173
174 return includeResult{
175 name: templ.Name(),
176 result: result,
177 }
178 }
179
180 // IncludeCached executes and caches partial templates. The cache is created with name+variants as the key.
181 // Note that ctx is provided by Hugo, not the end user.
182 func (ns *Namespace) IncludeCached(ctx context.Context, name string, context any, variants ...any) (any, error) {
183 start := time.Now()
184 keyString := name
185 if len(variants) > 0 {
186 key := partialCacheKey{
187 Name: name,
188 Variants: variants,
189 }
190 keyString = key.Key()
191 }
192
193 depsManagerIn := tpl.Context.GetDependencyManagerInCurrentScope(ctx)
194 ti, err := ns.lookup(name)
195 if err != nil {
196 return nil, err
197 }
198
199 if parent := tpl.Context.CurrentTemplate.Get(ctx); parent != nil {
200 for parent != nil {
201 if parent.CurrentTemplateInfoOps == ti && parent.Key == keyString {
202 // This will deadlock if we continue.
203 return nil, fmt.Errorf("circular call stack detected in partial %q", ti.Filename())
204 }
205 parent = parent.Parent
206 }
207 }
208
209 r, found, err := ns.cachedPartials.cache.GetOrCreate(keyString, func(string) (includeResult, error) {
210 var depsManagerShared identity.Manager
211 if ns.deps.Conf.Watching() {
212 // We need to create a shared dependency manager to pass downwards
213 // and add those same dependencies to any cached invocation of this partial.
214 depsManagerShared = identity.NewManager()
215 ctx = tpl.Context.DependencyManagerScopedProvider.Set(ctx, depsManagerShared.(identity.DependencyManagerScopedProvider))
216 }
217 // Mark the ctx so templates.Defer can reject being called from a cached body.
218 ctx = tpl.Context.IsInPartialCached.Set(ctx, true)
219 r := ns.doInclude(ctx, keyString, ti, context)
220 if ns.deps.Conf.Watching() {
221 r.mangager = depsManagerShared
222 }
223 return r, r.err
224 })
225 if err != nil {
226 return nil, err
227 }
228
229 if ns.deps.Metrics != nil {
230 if found {
231 // The templates that gets executed is measured in Execute.
232 // We need to track the time spent in the cache to
233 // get the totals correct.
234 ns.deps.Metrics.MeasureSince(r.name, start)
235 }
236 ns.deps.Metrics.TrackValue(r.name, r.result, found)
237 }
238
239 if r.mangager != nil && depsManagerIn != nil {
240 depsManagerIn.AddIdentity(r.mangager)
241 }
242
243 return r.result, nil
244 }