| 1 |
// Copyright 2018 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 templates provides template functions for working with templates. |
| 15 |
package templates |
| 16 |
|
| 17 |
import ( |
| 18 |
"context" |
| 19 |
"fmt" |
| 20 |
htmltemplate "html/template" |
| 21 |
"strconv" |
| 22 |
"sync/atomic" |
| 23 |
|
| 24 |
"github.com/gohugoio/hugo/tpl/tplimpl" |
| 25 |
|
| 26 |
"github.com/gohugoio/hugo/common/hashing" |
| 27 |
"github.com/gohugoio/hugo/deps" |
| 28 |
"github.com/gohugoio/hugo/tpl" |
| 29 |
"github.com/gohugoio/hugo/tpl/partials" |
| 30 |
"github.com/mitchellh/mapstructure" |
| 31 |
) |
| 32 |
|
| 33 |
// New returns a new instance of the templates-namespaced template functions. |
| 34 |
func New(deps *deps.Deps) *Namespace { |
| 35 |
ns := &Namespace{ |
| 36 |
deps: deps, |
| 37 |
} |
| 38 |
|
| 39 |
return ns |
| 40 |
} |
| 41 |
|
| 42 |
// Namespace provides template functions for the "templates" namespace. |
| 43 |
type Namespace struct { |
| 44 |
deps *deps.Deps |
| 45 |
partialsNs *partials.Namespace |
| 46 |
} |
| 47 |
|
| 48 |
// Exists returns whether the template with the given name exists. |
| 49 |
// Note that this is the Unix-styled relative path including filename suffix, |
| 50 |
// e.g. partials/header.html |
| 51 |
func (ns *Namespace) Exists(name string) bool { |
| 52 |
return ns.deps.GetTemplateStore().HasTemplate(name) |
| 53 |
} |
| 54 |
|
| 55 |
// Defer defers the execution of a template block. |
| 56 |
func (ns *Namespace) Defer(ctx context.Context, args ...any) (bool, error) { |
| 57 |
// Prevent defer from being used in content adapters, |
| 58 |
// that just doesn't work. |
| 59 |
ns.deps.Site.CheckReady() |
| 60 |
|
| 61 |
// Reject use inside a partialCached body: the cached output retains the |
| 62 |
// deferred placeholder across rebuilds while the executions map is reset, |
| 63 |
// which used to cause a panic in executeDeferredTemplates. See issue #13492. |
| 64 |
if tpl.Context.IsInPartialCached.Get(ctx) { |
| 65 |
return false, fmt.Errorf("templates.Defer cannot be used inside a partialCached partial; use partial instead, or move templates.Defer to the calling template") |
| 66 |
} |
| 67 |
|
| 68 |
if len(args) != 0 { |
| 69 |
return false, fmt.Errorf("Defer does not take any arguments") |
| 70 |
} |
| 71 |
return true, nil |
| 72 |
} |
| 73 |
|
| 74 |
var defferedIDCounter atomic.Uint64 |
| 75 |
|
| 76 |
type DeferOpts struct { |
| 77 |
// Optional cache key. If set, the deferred block will be executed |
| 78 |
// once per unique key. |
| 79 |
Key string |
| 80 |
|
| 81 |
// Optional data context to use when executing the deferred block. |
| 82 |
Data any |
| 83 |
} |
| 84 |
|
| 85 |
// Inner executes the inner content of a partial decorator. |
| 86 |
// Note that there is only one inner block per partial decorator, but inner may be called multiple times with, typically, different data. |
| 87 |
func (ns *Namespace) Inner(ctx context.Context, data any) (any, error) { |
| 88 |
stack := tpl.Context.PartialDecoratorIDStack.Get(ctx) |
| 89 |
id, ok := stack.Peek() |
| 90 |
if !ok { |
| 91 |
panic("no partial decorator ID on stack") |
| 92 |
} |
| 93 |
|
| 94 |
// Signal that inner exists. |
| 95 |
id.Bool = true |
| 96 |
|
| 97 |
partialName := fmt.Sprintf("%s%s", tplimpl.PartialDecoratorPrefix, id.Str) |
| 98 |
|
| 99 |
v, err := ns.partialsNs.Include(ctx, partialName, data) |
| 100 |
|
| 101 |
return v, err |
| 102 |
} |
| 103 |
|
| 104 |
// For internal use only. |
| 105 |
func (ns *Namespace) _PushPartialDecorator(ctx context.Context, id string) (any, error) { |
| 106 |
tpl.Context.PartialDecoratorIDStack.Get(ctx).Push(&tpl.StringBool{Str: id, Bool: false}) |
| 107 |
return "", nil |
| 108 |
} |
| 109 |
|
| 110 |
// For internal use only. |
| 111 |
func (ns *Namespace) _PopPartialDecorator(ctx context.Context, id string) any { |
| 112 |
stack := tpl.Context.PartialDecoratorIDStack.Get(ctx) |
| 113 |
if stack == nil || stack.Len() == 0 { |
| 114 |
panic("decorator stack is nil or empty") |
| 115 |
} |
| 116 |
|
| 117 |
// The stack is tied to the context, so no data race. |
| 118 |
top, ok := stack.Pop() |
| 119 |
if !ok || top.Str != id { |
| 120 |
panic("partial decorator ID mismatch") |
| 121 |
} |
| 122 |
if !top.Bool { |
| 123 |
// Prevents anything being rendered if inner was not called. |
| 124 |
// Use template.JS to avoid Go's html/template JS escaper |
| 125 |
// wrapping an empty string in quotes inside <script> tags. |
| 126 |
// See https://github.com/gohugoio/hugo/issues/14711 |
| 127 |
return htmltemplate.JS("") |
| 128 |
} |
| 129 |
return top.Bool // return whether inner exists in the wrapped partial. |
| 130 |
} |
| 131 |
|
| 132 |
// DoDefer defers the execution of a template block. |
| 133 |
// For internal use only. |
| 134 |
func (ns *Namespace) DoDefer(ctx context.Context, id string, optsv any) string { |
| 135 |
var opts DeferOpts |
| 136 |
if optsv != nil { |
| 137 |
if err := mapstructure.WeakDecode(optsv, &opts); err != nil { |
| 138 |
panic(err) |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
templateName := id |
| 143 |
var key string |
| 144 |
if opts.Key != "" { |
| 145 |
key = hashing.XxHashFromStringHexEncoded(opts.Key) |
| 146 |
} else { |
| 147 |
key = strconv.FormatUint(defferedIDCounter.Add(1), 10) |
| 148 |
} |
| 149 |
|
| 150 |
id = fmt.Sprintf("%s_%s%s", id, key, tpl.HugoDeferredTemplateSuffix) |
| 151 |
|
| 152 |
_, _ = ns.deps.BuildState.DeferredExecutions.Executions.GetOrCreate(id, |
| 153 |
func() (*tpl.DeferredExecution, error) { |
| 154 |
return &tpl.DeferredExecution{ |
| 155 |
TemplatePath: templateName, |
| 156 |
Ctx: ctx, |
| 157 |
Data: opts.Data, |
| 158 |
Executed: false, |
| 159 |
}, nil |
| 160 |
}) |
| 161 |
|
| 162 |
return id |
| 163 |
} |
| 164 |
|
| 165 |
// Get information about the currently executing template. |
| 166 |
func (ns *Namespace) Current(ctx context.Context) *tpl.CurrentTemplateInfo { |
| 167 |
return tpl.Context.CurrentTemplate.Get(ctx) |
| 168 |
} |