| 1 |
// Copyright 2025 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 hugolib |
| 15 |
|
| 16 |
import ( |
| 17 |
"bytes" |
| 18 |
"context" |
| 19 |
"errors" |
| 20 |
"fmt" |
| 21 |
"html/template" |
| 22 |
"path" |
| 23 |
"reflect" |
| 24 |
"regexp" |
| 25 |
"sort" |
| 26 |
"strconv" |
| 27 |
"strings" |
| 28 |
"sync" |
| 29 |
|
| 30 |
"github.com/bep/helpers/maphelpers" |
| 31 |
"github.com/gohugoio/hugo/common/herrors" |
| 32 |
"github.com/gohugoio/hugo/common/hstore" |
| 33 |
"github.com/gohugoio/hugo/common/types" |
| 34 |
"github.com/gohugoio/hugo/deps" |
| 35 |
"github.com/gohugoio/hugo/tpl/tplimpl" |
| 36 |
|
| 37 |
"github.com/gohugoio/hugo/parser/pageparser" |
| 38 |
"github.com/gohugoio/hugo/resources/page" |
| 39 |
|
| 40 |
"github.com/gohugoio/hugo/common/text" |
| 41 |
"github.com/gohugoio/hugo/common/urls" |
| 42 |
|
| 43 |
bp "github.com/gohugoio/hugo/bufferpool" |
| 44 |
"github.com/gohugoio/hugo/tpl" |
| 45 |
) |
| 46 |
|
| 47 |
var ( |
| 48 |
_ urls.RefLinker = (*ShortcodeWithPage)(nil) |
| 49 |
_ types.Unwrapper = (*ShortcodeWithPage)(nil) |
| 50 |
_ text.Positioner = (*ShortcodeWithPage)(nil) |
| 51 |
_ hstore.StoreProvider = (*ShortcodeWithPage)(nil) |
| 52 |
) |
| 53 |
|
| 54 |
// ShortcodeWithPage is the "." context in a shortcode template. |
| 55 |
type ShortcodeWithPage struct { |
| 56 |
Params any |
| 57 |
Inner template.HTML |
| 58 |
Page page.Page |
| 59 |
Parent *ShortcodeWithPage |
| 60 |
Name string |
| 61 |
IsNamedParams bool |
| 62 |
|
| 63 |
// Zero-based ordinal in relation to its parent. If the parent is the page itself, |
| 64 |
// this ordinal will represent the position of this shortcode in the page content. |
| 65 |
Ordinal int |
| 66 |
|
| 67 |
// Indentation before the opening shortcode in the source. |
| 68 |
indentation string |
| 69 |
|
| 70 |
innerDeindentInit sync.Once |
| 71 |
innerDeindent template.HTML |
| 72 |
|
| 73 |
// pos is the position in bytes in the source file. Used for error logging. |
| 74 |
posInit sync.Once |
| 75 |
posOffset int |
| 76 |
pos text.Position |
| 77 |
|
| 78 |
store *hstore.Scratch |
| 79 |
} |
| 80 |
|
| 81 |
// InnerDeindent returns the (potentially de-indented) inner content of the shortcode. |
| 82 |
func (scp *ShortcodeWithPage) InnerDeindent() template.HTML { |
| 83 |
if scp.indentation == "" { |
| 84 |
return scp.Inner |
| 85 |
} |
| 86 |
scp.innerDeindentInit.Do(func() { |
| 87 |
b := bp.GetBuffer() |
| 88 |
text.VisitLinesAfter(string(scp.Inner), func(s string) { |
| 89 |
if after, ok := strings.CutPrefix(s, scp.indentation); ok { |
| 90 |
b.WriteString(after) |
| 91 |
} else { |
| 92 |
b.WriteString(s) |
| 93 |
} |
| 94 |
}) |
| 95 |
scp.innerDeindent = template.HTML(b.String()) |
| 96 |
bp.PutBuffer(b) |
| 97 |
}) |
| 98 |
|
| 99 |
return scp.innerDeindent |
| 100 |
} |
| 101 |
|
| 102 |
// Position returns this shortcode's detailed position. Note that this information |
| 103 |
// may be expensive to calculate, so only use this in error situations. |
| 104 |
func (scp *ShortcodeWithPage) Position() text.Position { |
| 105 |
scp.posInit.Do(func() { |
| 106 |
if p, ok := mustUnwrapPage(scp.Page).(pageContext); ok { |
| 107 |
scp.pos = p.posOffset(scp.posOffset) |
| 108 |
} |
| 109 |
}) |
| 110 |
return scp.pos |
| 111 |
} |
| 112 |
|
| 113 |
// Site returns information about the current site. |
| 114 |
func (scp *ShortcodeWithPage) Site() page.Site { |
| 115 |
return scp.Page.Site() |
| 116 |
} |
| 117 |
|
| 118 |
// Ref is a shortcut to the Ref method on Page. It passes itself as a context |
| 119 |
// to get better error messages. |
| 120 |
func (scp *ShortcodeWithPage) Ref(args map[string]any) (string, error) { |
| 121 |
return scp.Page.RefFrom(args, scp) |
| 122 |
} |
| 123 |
|
| 124 |
// RelRef is a shortcut to the RelRef method on Page. It passes itself as a context |
| 125 |
// to get better error messages. |
| 126 |
func (scp *ShortcodeWithPage) RelRef(args map[string]any) (string, error) { |
| 127 |
return scp.Page.RelRefFrom(args, scp) |
| 128 |
} |
| 129 |
|
| 130 |
// Store returns this shortcode's Store. |
| 131 |
func (scp *ShortcodeWithPage) Store() *hstore.Scratch { |
| 132 |
if scp.store == nil { |
| 133 |
scp.store = hstore.NewScratch() |
| 134 |
} |
| 135 |
return scp.store |
| 136 |
} |
| 137 |
|
| 138 |
// Scratch returns a scratch-pad scoped for this shortcode. This can be used |
| 139 |
// as a temporary storage for variables, counters etc. |
| 140 |
// Deprecated: Use Store instead. Note that from the templates this should be considered a "soft deprecation". |
| 141 |
func (scp *ShortcodeWithPage) Scratch() *hstore.Scratch { |
| 142 |
return scp.Store() |
| 143 |
} |
| 144 |
|
| 145 |
// Get is a convenience method to look up shortcode parameters by its key. |
| 146 |
func (scp *ShortcodeWithPage) Get(key any) any { |
| 147 |
if scp.Params == nil { |
| 148 |
return nil |
| 149 |
} |
| 150 |
if reflect.ValueOf(scp.Params).Len() == 0 { |
| 151 |
return nil |
| 152 |
} |
| 153 |
|
| 154 |
var x reflect.Value |
| 155 |
|
| 156 |
switch key.(type) { |
| 157 |
case int64, int32, int16, int8, int: |
| 158 |
if reflect.TypeOf(scp.Params).Kind() == reflect.Map { |
| 159 |
// We treat this as a non error, so people can do similar to |
| 160 |
// {{ $myParam := .Get "myParam" | default .Get 0 }} |
| 161 |
// Without having to do additional checks. |
| 162 |
return nil |
| 163 |
} else if reflect.TypeOf(scp.Params).Kind() == reflect.Slice { |
| 164 |
idx := int(reflect.ValueOf(key).Int()) |
| 165 |
ln := reflect.ValueOf(scp.Params).Len() |
| 166 |
if idx > ln-1 { |
| 167 |
return "" |
| 168 |
} |
| 169 |
x = reflect.ValueOf(scp.Params).Index(idx) |
| 170 |
} |
| 171 |
case string: |
| 172 |
if reflect.TypeOf(scp.Params).Kind() == reflect.Map { |
| 173 |
x = reflect.ValueOf(scp.Params).MapIndex(reflect.ValueOf(key)) |
| 174 |
if !x.IsValid() { |
| 175 |
return "" |
| 176 |
} |
| 177 |
} else if reflect.TypeOf(scp.Params).Kind() == reflect.Slice { |
| 178 |
// We treat this as a non error, so people can do similar to |
| 179 |
// {{ $myParam := .Get "myParam" | default .Get 0 }} |
| 180 |
// Without having to do additional checks. |
| 181 |
return nil |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
return x.Interface() |
| 186 |
} |
| 187 |
|
| 188 |
// For internal use only. |
| 189 |
func (scp *ShortcodeWithPage) Unwrapv() any { |
| 190 |
return scp.Page |
| 191 |
} |
| 192 |
|
| 193 |
// Note - this value must not contain any markup syntax |
| 194 |
const shortcodePlaceholderPrefix = "HAHAHUGOSHORTCODE" |
| 195 |
|
| 196 |
func createShortcodePlaceholder(sid string, id, ordinal uint64) string { |
| 197 |
return shortcodePlaceholderPrefix + strconv.FormatUint(id, 10) + sid + strconv.FormatUint(ordinal, 10) + "HBHB" |
| 198 |
} |
| 199 |
|
| 200 |
type shortcode struct { |
| 201 |
name string |
| 202 |
isInline bool // inline shortcode. Any inner will be a Go template. |
| 203 |
isClosing bool // whether a closing tag was provided |
| 204 |
inner []any // string or nested shortcode |
| 205 |
params any // map or array |
| 206 |
ordinal int |
| 207 |
|
| 208 |
indentation string // indentation from source. |
| 209 |
|
| 210 |
templ *tplimpl.TemplInfo |
| 211 |
|
| 212 |
// If set, the rendered shortcode is sent as part of the surrounding content |
| 213 |
// to Goldmark and similar. |
| 214 |
// Before Hug0 0.55 we didn't send any shortcode output to the markup |
| 215 |
// renderer, and this flag told Hugo to process the {{ .Inner }} content |
| 216 |
// separately. |
| 217 |
// The old behavior can be had by starting your shortcode template with: |
| 218 |
// {{ $_hugo_config := `{ "version": 1 }`}} |
| 219 |
doMarkup bool |
| 220 |
|
| 221 |
// the placeholder in the source when passed to Goldmark etc. |
| 222 |
// This also identifies the rendered shortcode. |
| 223 |
placeholder string |
| 224 |
|
| 225 |
pos int // the position in bytes in the source file |
| 226 |
length int // the length in bytes in the source file |
| 227 |
} |
| 228 |
|
| 229 |
func (s shortcode) insertPlaceholder() bool { |
| 230 |
return !s.doMarkup || s.configVersion() == 1 |
| 231 |
} |
| 232 |
|
| 233 |
func (s shortcode) needsInner() bool { |
| 234 |
return s.templ != nil && s.templ.ParseInfo.IsInner |
| 235 |
} |
| 236 |
|
| 237 |
func (s shortcode) configVersion() int { |
| 238 |
if s.templ == nil { |
| 239 |
// Not set for inline shortcodes. |
| 240 |
return 2 |
| 241 |
} |
| 242 |
return s.templ.ParseInfo.Config.Version |
| 243 |
} |
| 244 |
|
| 245 |
func (s shortcode) innerString() string { |
| 246 |
var sb strings.Builder |
| 247 |
|
| 248 |
for _, inner := range s.inner { |
| 249 |
sb.WriteString(inner.(string)) |
| 250 |
} |
| 251 |
|
| 252 |
return sb.String() |
| 253 |
} |
| 254 |
|
| 255 |
func (sc shortcode) String() string { |
| 256 |
// for testing (mostly), so any change here will break tests! |
| 257 |
var params any |
| 258 |
switch v := sc.params.(type) { |
| 259 |
case map[string]any: |
| 260 |
// sort the keys so test assertions won't fail |
| 261 |
var keys []string |
| 262 |
for k := range v { |
| 263 |
keys = append(keys, k) |
| 264 |
} |
| 265 |
sort.Strings(keys) |
| 266 |
tmp := make(map[string]any) |
| 267 |
|
| 268 |
for _, k := range keys { |
| 269 |
tmp[k] = v[k] |
| 270 |
} |
| 271 |
params = tmp |
| 272 |
|
| 273 |
default: |
| 274 |
// use it as is |
| 275 |
params = sc.params |
| 276 |
} |
| 277 |
|
| 278 |
return fmt.Sprintf("%s(%q, %t){%s}", sc.name, params, sc.doMarkup, sc.inner) |
| 279 |
} |
| 280 |
|
| 281 |
// shared between all pages from the same source file. |
| 282 |
type shortcodeParseInfo struct { |
| 283 |
filename string |
| 284 |
firstTemplateStore *tplimpl.TemplateStore // This represents the first site and must not be used for execution. |
| 285 |
|
| 286 |
// Ordered list of shortcodes. |
| 287 |
shortcodes []*shortcode |
| 288 |
|
| 289 |
// All the shortcode names in this set. |
| 290 |
nameSet *maphelpers.ConcurrentSet[string] |
| 291 |
|
| 292 |
// Configuration |
| 293 |
enableInlineShortcodes bool |
| 294 |
} |
| 295 |
|
| 296 |
func (s *shortcodeParseInfo) addName(name string) { |
| 297 |
s.nameSet.Add(name) |
| 298 |
} |
| 299 |
|
| 300 |
func (s *shortcodeParseInfo) hasName(name string) bool { |
| 301 |
return s.nameSet.Has(name) |
| 302 |
} |
| 303 |
|
| 304 |
func newShortcodeHandler(filename string, d *deps.Deps) *shortcodeParseInfo { |
| 305 |
sh := &shortcodeParseInfo{ |
| 306 |
filename: filename, |
| 307 |
firstTemplateStore: d.TemplateStore, |
| 308 |
enableInlineShortcodes: d.ExecHelper.Sec().EnableInlineShortcodes, |
| 309 |
shortcodes: make([]*shortcode, 0, 4), |
| 310 |
nameSet: maphelpers.NewConcurrentSet[string](), |
| 311 |
} |
| 312 |
|
| 313 |
return sh |
| 314 |
} |
| 315 |
|
| 316 |
const ( |
| 317 |
innerNewlineRegexp = "\n" |
| 318 |
innerCleanupRegexp = `\A<p>(.*)</p>\n\z` |
| 319 |
innerCleanupExpand = "$1" |
| 320 |
) |
| 321 |
|
| 322 |
func prepareShortcode( |
| 323 |
level int, |
| 324 |
sc *shortcode, |
| 325 |
parent *ShortcodeWithPage, |
| 326 |
po *pageOutput, |
| 327 |
isRenderString bool, |
| 328 |
) (shortcodeRenderer, error) { |
| 329 |
p := po.p |
| 330 |
toParseErr := func(err error) error { |
| 331 |
source := p.m.content.mustSource() |
| 332 |
return p.parseError(fmt.Errorf("failed to render shortcode %q: %w", sc.name, err), source, sc.pos) |
| 333 |
} |
| 334 |
|
| 335 |
// Allow the caller to delay the rendering of the shortcode if needed. |
| 336 |
var fn shortcodeRenderFunc = func(ctx context.Context) ([]byte, bool, error) { |
| 337 |
if p.m.pageConfigSource.ContentMediaType.IsMarkdown() && sc.doMarkup { |
| 338 |
// Signal downwards that the content rendered will be |
| 339 |
// parsed and rendered by Goldmark. |
| 340 |
ctx = tpl.Context.IsInGoldmark.Set(ctx, true) |
| 341 |
} |
| 342 |
r, err := doRenderShortcode(ctx, level, po.p.s.TemplateStore, sc, parent, po, isRenderString) |
| 343 |
if err != nil { |
| 344 |
return nil, false, toParseErr(err) |
| 345 |
} |
| 346 |
|
| 347 |
b, hasVariants, err := r.renderShortcode(ctx) |
| 348 |
if err != nil { |
| 349 |
return nil, false, toParseErr(err) |
| 350 |
} |
| 351 |
return b, hasVariants, nil |
| 352 |
} |
| 353 |
|
| 354 |
return fn, nil |
| 355 |
} |
| 356 |
|
| 357 |
func doRenderShortcode( |
| 358 |
ctx context.Context, |
| 359 |
level int, |
| 360 |
ts *tplimpl.TemplateStore, |
| 361 |
sc *shortcode, |
| 362 |
parent *ShortcodeWithPage, |
| 363 |
po *pageOutput, |
| 364 |
isRenderString bool, |
| 365 |
) (shortcodeRenderer, error) { |
| 366 |
var tmpl *tplimpl.TemplInfo |
| 367 |
p := po.p |
| 368 |
|
| 369 |
// Tracks whether this shortcode or any of its children has template variations |
| 370 |
// in other languages or output formats. We are currently only interested in |
| 371 |
// the output formats. |
| 372 |
var hasVariants bool |
| 373 |
|
| 374 |
if sc.isInline { |
| 375 |
if !p.s.ExecHelper.Sec().EnableInlineShortcodes { |
| 376 |
return zeroShortcode, nil |
| 377 |
} |
| 378 |
templatePath := path.Join("_inline_shortcode", p.Path(), sc.name) |
| 379 |
if sc.isClosing { |
| 380 |
templStr := sc.innerString() |
| 381 |
|
| 382 |
var err error |
| 383 |
tmpl, err = ts.TextParse(templatePath, templStr) |
| 384 |
if err != nil { |
| 385 |
if isRenderString { |
| 386 |
return zeroShortcode, p.wrapError(err) |
| 387 |
} |
| 388 |
fe := herrors.NewFileErrorFromName(err, p.File().Filename()) |
| 389 |
pos := fe.Position() |
| 390 |
pos.LineNumber += p.posOffset(sc.pos).LineNumber |
| 391 |
fe = fe.UpdatePosition(pos) |
| 392 |
return zeroShortcode, p.wrapError(fe) |
| 393 |
} |
| 394 |
|
| 395 |
} else { |
| 396 |
// Re-use of shortcode defined earlier in the same page. |
| 397 |
tmpl = ts.TextLookup(templatePath) |
| 398 |
if tmpl == nil { |
| 399 |
return zeroShortcode, fmt.Errorf("no earlier definition of shortcode %q found", sc.name) |
| 400 |
} |
| 401 |
} |
| 402 |
} else { |
| 403 |
ofCount := map[string]int{} |
| 404 |
include := func(match *tplimpl.TemplInfo) bool { |
| 405 |
ofCount[match.D.OutputFormat]++ |
| 406 |
return true |
| 407 |
} |
| 408 |
base, layoutDescriptor := po.GetInternalTemplateBasePathAndDescriptor() |
| 409 |
|
| 410 |
// With shortcodes/mymarkdown.md (only), this allows {{% mymarkdown %}} when rendering HTML, |
| 411 |
// but will not resolve any template when doing {{< mymarkdown >}}. |
| 412 |
layoutDescriptor.AlwaysAllowPlainText = sc.doMarkup |
| 413 |
q := tplimpl.TemplateQuery{ |
| 414 |
Path: base, |
| 415 |
Name: sc.name, |
| 416 |
Category: tplimpl.CategoryShortcode, |
| 417 |
Desc: layoutDescriptor, |
| 418 |
Sites: p.s.siteVector, |
| 419 |
Consider: include, |
| 420 |
} |
| 421 |
v, err := ts.LookupShortcode(q) |
| 422 |
if v == nil { |
| 423 |
return zeroShortcode, err |
| 424 |
} |
| 425 |
tmpl = v |
| 426 |
hasVariants = hasVariants || len(ofCount) > 1 |
| 427 |
} |
| 428 |
|
| 429 |
data := &ShortcodeWithPage{ |
| 430 |
Ordinal: sc.ordinal, |
| 431 |
posOffset: sc.pos, |
| 432 |
indentation: sc.indentation, |
| 433 |
Params: sc.params, |
| 434 |
Page: newPageForShortcode(p), |
| 435 |
Parent: parent, |
| 436 |
Name: sc.name, |
| 437 |
} |
| 438 |
|
| 439 |
if sc.params != nil { |
| 440 |
data.IsNamedParams = reflect.TypeOf(sc.params).Kind() == reflect.Map |
| 441 |
} |
| 442 |
|
| 443 |
if len(sc.inner) > 0 { |
| 444 |
var inner strings.Builder |
| 445 |
for _, innerData := range sc.inner { |
| 446 |
switch innerData := innerData.(type) { |
| 447 |
case string: |
| 448 |
inner.WriteString(innerData) |
| 449 |
case *shortcode: |
| 450 |
s, err := prepareShortcode(level+1, innerData, data, po, isRenderString) |
| 451 |
if err != nil { |
| 452 |
return zeroShortcode, err |
| 453 |
} |
| 454 |
ss, more, err := s.renderShortcodeString(ctx) |
| 455 |
hasVariants = hasVariants || more |
| 456 |
if err != nil { |
| 457 |
return zeroShortcode, err |
| 458 |
} |
| 459 |
inner.WriteString(ss) |
| 460 |
default: |
| 461 |
po.p.s.Log.Errorf("Illegal state on shortcode rendering of %q in page %q. Illegal type in inner data: %s ", |
| 462 |
sc.name, p.File().Path(), reflect.TypeOf(innerData)) |
| 463 |
return zeroShortcode, nil |
| 464 |
} |
| 465 |
} |
| 466 |
|
| 467 |
// Pre Hugo 0.55 this was the behavior even for the outer-most |
| 468 |
// shortcode. |
| 469 |
if sc.doMarkup && (level > 0 || sc.configVersion() == 1) { |
| 470 |
var err error |
| 471 |
b, err := p.pageOutput.contentRenderer.ParseAndRenderContent(ctx, []byte(inner.String()), false) |
| 472 |
if err != nil { |
| 473 |
return zeroShortcode, err |
| 474 |
} |
| 475 |
|
| 476 |
newInner := b.Bytes() |
| 477 |
|
| 478 |
// If the type is “” (unknown) or “markdown”, we assume the markdown |
| 479 |
// generation has been performed. Given the input: `a line`, markdown |
| 480 |
// specifies the HTML `<p>a line</p>\n`. When dealing with documents as a |
| 481 |
// whole, this is OK. When dealing with an `{{ .Inner }}` block in Hugo, |
| 482 |
// this is not so good. This code does two things: |
| 483 |
// |
| 484 |
// 1. Check to see if inner has a newline in it. If so, the Inner data is |
| 485 |
// unchanged. |
| 486 |
// 2 If inner does not have a newline, strip the wrapping <p> block and |
| 487 |
// the newline. |
| 488 |
switch p.m.pageConfigSource.Content.Markup { |
| 489 |
case "", "markdown": |
| 490 |
if match, _ := regexp.MatchString(innerNewlineRegexp, inner.String()); !match { |
| 491 |
cleaner, err := regexp.Compile(innerCleanupRegexp) |
| 492 |
|
| 493 |
if err == nil { |
| 494 |
newInner = cleaner.ReplaceAll(newInner, []byte(innerCleanupExpand)) |
| 495 |
} |
| 496 |
} |
| 497 |
} |
| 498 |
|
| 499 |
// TODO(bep) we may have plain text inner templates. |
| 500 |
data.Inner = template.HTML(newInner) |
| 501 |
} else { |
| 502 |
data.Inner = template.HTML(inner.String()) |
| 503 |
} |
| 504 |
|
| 505 |
} |
| 506 |
|
| 507 |
result, err := renderShortcodeWithPage(ctx, ts, tmpl, data) |
| 508 |
|
| 509 |
if err != nil && sc.isInline { |
| 510 |
fe := herrors.NewFileErrorFromName(err, p.File().Filename()) |
| 511 |
pos := fe.Position() |
| 512 |
pos.LineNumber += p.posOffset(sc.pos).LineNumber |
| 513 |
fe = fe.UpdatePosition(pos) |
| 514 |
return zeroShortcode, fe |
| 515 |
} |
| 516 |
|
| 517 |
if len(sc.inner) == 0 && len(sc.indentation) > 0 { |
| 518 |
b := bp.GetBuffer() |
| 519 |
i := 0 |
| 520 |
text.VisitLinesAfter(result, func(line string) { |
| 521 |
// The first line is correctly indented. |
| 522 |
if i > 0 { |
| 523 |
b.WriteString(sc.indentation) |
| 524 |
} |
| 525 |
i++ |
| 526 |
b.WriteString(line) |
| 527 |
}) |
| 528 |
|
| 529 |
result = b.String() |
| 530 |
bp.PutBuffer(b) |
| 531 |
} |
| 532 |
|
| 533 |
return prerenderedShortcode{s: result, hasVariants: hasVariants}, err |
| 534 |
} |
| 535 |
|
| 536 |
func (s *shortcodeParseInfo) prepareShortcodesForPage(po *pageOutput, isRenderString bool) (map[string]shortcodeRenderer, error) { |
| 537 |
rendered := make(map[string]shortcodeRenderer) |
| 538 |
|
| 539 |
for _, v := range s.shortcodes { |
| 540 |
s, err := prepareShortcode(0, v, nil, po, isRenderString) |
| 541 |
if err != nil { |
| 542 |
return nil, err |
| 543 |
} |
| 544 |
rendered[v.placeholder] = s |
| 545 |
} |
| 546 |
|
| 547 |
return rendered, nil |
| 548 |
} |
| 549 |
|
| 550 |
func posFromInput(filename string, input []byte, offset int) text.Position { |
| 551 |
if offset < 0 || offset > len(input) { |
| 552 |
return text.Position{ |
| 553 |
Filename: filename, |
| 554 |
} |
| 555 |
} |
| 556 |
lf := []byte("\n") |
| 557 |
input = input[:offset] |
| 558 |
lineNumber := bytes.Count(input, lf) + 1 |
| 559 |
endOfLastLine := bytes.LastIndex(input, lf) |
| 560 |
|
| 561 |
return text.Position{ |
| 562 |
Filename: filename, |
| 563 |
LineNumber: lineNumber, |
| 564 |
ColumnNumber: offset - endOfLastLine, |
| 565 |
Offset: offset, |
| 566 |
} |
| 567 |
} |
| 568 |
|
| 569 |
// pageTokens state: |
| 570 |
// - before: positioned just before the shortcode start |
| 571 |
// - after: shortcode(s) consumed (plural when they are nested) |
| 572 |
func (s *shortcodeParseInfo) extractShortcode(ordinal, level int, source []byte, pt *pageparser.Iterator) (*shortcode, error) { |
| 573 |
if s == nil { |
| 574 |
panic("handler nil") |
| 575 |
} |
| 576 |
sc := &shortcode{ordinal: ordinal} |
| 577 |
|
| 578 |
// Back up one to identify any indentation. |
| 579 |
if pt.Pos() > 0 { |
| 580 |
pt.Backup() |
| 581 |
item := pt.Next() |
| 582 |
if item.IsIndentation() { |
| 583 |
sc.indentation = item.ValStr(source) |
| 584 |
} |
| 585 |
} |
| 586 |
|
| 587 |
cnt := 0 |
| 588 |
nestedOrdinal := 0 |
| 589 |
nextLevel := level + 1 |
| 590 |
closed := false |
| 591 |
const errorPrefix = "failed to extract shortcode" |
| 592 |
|
| 593 |
Loop: |
| 594 |
for { |
| 595 |
currItem := pt.Next() |
| 596 |
switch { |
| 597 |
case currItem.IsLeftShortcodeDelim(): |
| 598 |
next := pt.Peek() |
| 599 |
if next.IsRightShortcodeDelim() { |
| 600 |
// no name: {{< >}} or {{% %}} |
| 601 |
return sc, errors.New("shortcode has no name") |
| 602 |
} |
| 603 |
if next.IsShortcodeClose() { |
| 604 |
continue |
| 605 |
} |
| 606 |
|
| 607 |
if cnt > 0 { |
| 608 |
// nested shortcode; append it to inner content |
| 609 |
pt.Backup() |
| 610 |
nested, err := s.extractShortcode(nestedOrdinal, nextLevel, source, pt) |
| 611 |
nestedOrdinal++ |
| 612 |
if nested != nil && nested.name != "" { |
| 613 |
s.addName(nested.name) |
| 614 |
} |
| 615 |
|
| 616 |
if err == nil { |
| 617 |
sc.inner = append(sc.inner, nested) |
| 618 |
} else { |
| 619 |
return sc, err |
| 620 |
} |
| 621 |
|
| 622 |
} else { |
| 623 |
sc.doMarkup = currItem.IsShortcodeMarkupDelimiter() |
| 624 |
} |
| 625 |
|
| 626 |
cnt++ |
| 627 |
|
| 628 |
case currItem.IsRightShortcodeDelim(): |
| 629 |
// we trust the template on this: |
| 630 |
// if there's no inner, we're done |
| 631 |
if !sc.isInline { |
| 632 |
if !sc.templ.ParseInfo.IsInner { |
| 633 |
return sc, nil |
| 634 |
} |
| 635 |
} |
| 636 |
|
| 637 |
case currItem.IsShortcodeClose(): |
| 638 |
closed = true |
| 639 |
next := pt.Peek() |
| 640 |
if !sc.isInline { |
| 641 |
if !sc.needsInner() { |
| 642 |
if next.IsError() { |
| 643 |
// return that error, more specific |
| 644 |
continue |
| 645 |
} |
| 646 |
name := sc.name |
| 647 |
if name == "" { |
| 648 |
name = next.ValStr(source) |
| 649 |
} |
| 650 |
return nil, fmt.Errorf("%s: shortcode %q does not evaluate .Inner or .InnerDeindent, yet a closing tag was provided", errorPrefix, name) |
| 651 |
} |
| 652 |
} |
| 653 |
if next.IsRightShortcodeDelim() { |
| 654 |
// self-closing |
| 655 |
pt.Consume(1) |
| 656 |
} else { |
| 657 |
sc.isClosing = true |
| 658 |
pt.Consume(2) |
| 659 |
} |
| 660 |
return sc, nil |
| 661 |
case currItem.IsText(): |
| 662 |
sc.inner = append(sc.inner, currItem.ValStr(source)) |
| 663 |
case currItem.IsShortcodeName(): |
| 664 |
|
| 665 |
sc.name = currItem.ValStr(source) |
| 666 |
|
| 667 |
// Used to check if the template expects inner content, |
| 668 |
// so just pick one arbitrarily with the same name. |
| 669 |
templ := s.firstTemplateStore.LookupShortcodeByName(sc.name) |
| 670 |
if templ == nil { |
| 671 |
return nil, fmt.Errorf("%s: template for shortcode %q not found", errorPrefix, sc.name) |
| 672 |
} |
| 673 |
sc.templ = templ |
| 674 |
case currItem.IsInlineShortcodeName(): |
| 675 |
sc.name = currItem.ValStr(source) |
| 676 |
sc.isInline = true |
| 677 |
case currItem.IsShortcodeParam(): |
| 678 |
if !pt.IsValueNext() { |
| 679 |
continue |
| 680 |
} else if pt.Peek().IsShortcodeParamVal() { |
| 681 |
// named params |
| 682 |
if sc.params == nil { |
| 683 |
params := make(map[string]any) |
| 684 |
params[currItem.ValStr(source)] = pt.Next().ValTyped(source) |
| 685 |
sc.params = params |
| 686 |
} else { |
| 687 |
if params, ok := sc.params.(map[string]any); ok { |
| 688 |
params[currItem.ValStr(source)] = pt.Next().ValTyped(source) |
| 689 |
} else { |
| 690 |
return sc, fmt.Errorf("%s: invalid state: invalid param type %T for shortcode %q, expected a map", errorPrefix, params, sc.name) |
| 691 |
} |
| 692 |
} |
| 693 |
} else { |
| 694 |
// positional params |
| 695 |
if sc.params == nil { |
| 696 |
var params []any |
| 697 |
params = append(params, currItem.ValTyped(source)) |
| 698 |
sc.params = params |
| 699 |
} else { |
| 700 |
if params, ok := sc.params.([]any); ok { |
| 701 |
params = append(params, currItem.ValTyped(source)) |
| 702 |
sc.params = params |
| 703 |
} else { |
| 704 |
return sc, fmt.Errorf("%s: invalid state: invalid param type %T for shortcode %q, expected a slice", errorPrefix, params, sc.name) |
| 705 |
} |
| 706 |
} |
| 707 |
} |
| 708 |
case currItem.IsDone(): |
| 709 |
if !currItem.IsError() { |
| 710 |
if !closed && sc.needsInner() { |
| 711 |
return sc, fmt.Errorf("%s: shortcode %q must be closed or self-closed", errorPrefix, sc.name) |
| 712 |
} |
| 713 |
} |
| 714 |
// handled by caller |
| 715 |
pt.Backup() |
| 716 |
break Loop |
| 717 |
|
| 718 |
} |
| 719 |
} |
| 720 |
return sc, nil |
| 721 |
} |
| 722 |
|
| 723 |
// Replace prefixed shortcode tokens with the real content. |
| 724 |
// Note: This function will rewrite the input slice. |
| 725 |
func expandShortcodeTokens( |
| 726 |
ctx context.Context, |
| 727 |
source []byte, |
| 728 |
tokenHandler func(ctx context.Context, token string) ([]byte, error), |
| 729 |
) ([]byte, error) { |
| 730 |
start := 0 |
| 731 |
|
| 732 |
pre := []byte(shortcodePlaceholderPrefix) |
| 733 |
post := []byte("HBHB") |
| 734 |
pStart := []byte("<p>") |
| 735 |
pEnd := []byte("</p>") |
| 736 |
|
| 737 |
k := bytes.Index(source[start:], pre) |
| 738 |
|
| 739 |
for k != -1 { |
| 740 |
j := start + k |
| 741 |
postIdx := bytes.Index(source[j:], post) |
| 742 |
if postIdx < 0 { |
| 743 |
// this should never happen, but let the caller decide to panic or not |
| 744 |
return nil, errors.New("illegal state in content; shortcode token missing end delim") |
| 745 |
} |
| 746 |
|
| 747 |
end := j + postIdx + 4 |
| 748 |
key := string(source[j:end]) |
| 749 |
newVal, err := tokenHandler(ctx, key) |
| 750 |
if err != nil { |
| 751 |
return nil, err |
| 752 |
} |
| 753 |
|
| 754 |
// Issue #1148: Check for wrapping p-tags <p> |
| 755 |
if j >= 3 && bytes.Equal(source[j-3:j], pStart) { |
| 756 |
if (k+4) < len(source) && bytes.Equal(source[end:end+4], pEnd) { |
| 757 |
j -= 3 |
| 758 |
end += 4 |
| 759 |
} |
| 760 |
} |
| 761 |
|
| 762 |
// This and other cool slice tricks: https://github.com/golang/go/wiki/SliceTricks |
| 763 |
source = append(source[:j], append(newVal, source[end:]...)...) |
| 764 |
start = j |
| 765 |
k = bytes.Index(source[start:], pre) |
| 766 |
|
| 767 |
} |
| 768 |
|
| 769 |
return source, nil |
| 770 |
} |
| 771 |
|
| 772 |
func renderShortcodeWithPage(ctx context.Context, h *tplimpl.TemplateStore, tmpl *tplimpl.TemplInfo, data *ShortcodeWithPage) (string, error) { |
| 773 |
buffer := bp.GetBuffer() |
| 774 |
defer bp.PutBuffer(buffer) |
| 775 |
|
| 776 |
err := h.ExecuteWithContext(ctx, tmpl, buffer, data) |
| 777 |
if err != nil { |
| 778 |
return "", fmt.Errorf("failed to process shortcode: %w", err) |
| 779 |
} |
| 780 |
return buffer.String(), nil |
| 781 |
} |