Debian Codegraph @

hugolib/page__meta.go

raw
1 // Copyright 2024 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 "fmt"
18 "maps"
19 "path/filepath"
20 "regexp"
21 "strings"
22 "time"
23
24 "github.com/gobuffalo/flect"
25 "github.com/gohugoio/hugo/hugofs"
26 "github.com/gohugoio/hugo/hugofs/files"
27 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
28 "github.com/gohugoio/hugo/identity"
29 "github.com/gohugoio/hugo/langs"
30 "github.com/gohugoio/hugo/markup/converter"
31 "github.com/gohugoio/hugo/resources"
32
33 "github.com/gohugoio/hugo/source"
34
35 "github.com/gohugoio/hugo/common/hashing"
36 "github.com/gohugoio/hugo/common/hiter"
37 "github.com/gohugoio/hugo/common/hmaps"
38 "github.com/gohugoio/hugo/common/hugio"
39 "github.com/gohugoio/hugo/common/hugo"
40 "github.com/gohugoio/hugo/common/loggers"
41 "github.com/gohugoio/hugo/common/paths"
42 "github.com/gohugoio/hugo/config"
43 "github.com/gohugoio/hugo/helpers"
44
45 "github.com/gohugoio/hugo/output"
46 "github.com/gohugoio/hugo/resources/kinds"
47 "github.com/gohugoio/hugo/resources/page"
48 "github.com/gohugoio/hugo/resources/page/pagemeta"
49 "github.com/gohugoio/hugo/resources/resource"
50 "github.com/spf13/cast"
51 )
52
53 var cjkRe = regexp.MustCompile(`\p{Han}|\p{Hangul}|\p{Hiragana}|\p{Katakana}`)
54
55 func (m *pageMetaSource) GetIdentity() identity.Identity {
56 return m.pathInfo
57 }
58
59 func (m *pageMetaSource) Path() string {
60 return m.pathInfo.Base()
61 }
62
63 func (m *pageMetaSource) PathInfo() *paths.Path {
64 return m.pathInfo
65 }
66
67 func (m *pageMetaSource) forEeachContentNode(f func(v sitesmatrix.Vector, n contentNode) bool) bool {
68 return f(sitesmatrix.Vector{}, m)
69 }
70
71 type pageMetaSource struct {
72 pathInfo *paths.Path // Always set. This the canonical path to the Page.
73 f *source.File
74 pi *contentParseInfo
75 contentAdapterSourceEntryHash uint64
76
77 sitesMatrixBase sitesmatrix.VectorIterator
78 sitesMatrixBaseOnly bool
79
80 // Set for standalone pages, e.g. robotsTXT.
81 standaloneOutputFormat output.Format
82 resources.AtomicStaler
83
84 pageConfigSource *pagemeta.PageConfigEarly
85 cascadeCompiled *page.PageMatcherParamsConfigs
86
87 resourcePath string // Set for bundled pages; path relative to its bundle root.
88 bundled bool // Set if this page is bundled inside another.
89 noFrontMatter bool
90 openSource func() (hugio.ReadSeekCloser, error)
91 }
92
93 func (m *pageMetaSource) String() string {
94 if m.f != nil {
95 return fmt.Sprintf("pageMetaSource(%s, %s)", m.f.FileInfo().Meta().PathInfo, m.f.FileInfo().Meta().Filename)
96 }
97 return fmt.Sprintf("pageMetaSource(%s)", m.pathInfo)
98 }
99
100 func (m *pageMetaSource) contentWeight() int {
101 if m.f == nil {
102 return 0
103 }
104 return m.f.FileInfo().Meta().Weight
105 }
106
107 func (m *pageMetaSource) nodeCategoryPage() {
108 // Marker method.
109 }
110
111 func (m *pageMetaSource) nodeCategorySingle() {
112 // Marker method.
113 }
114
115 func (m *pageMetaSource) nodeSourceEntryID() any {
116 if m.f != nil && !m.f.IsContentAdapter() {
117 return m.f.FileInfo().Meta().Filename
118 }
119 return m.contentAdapterSourceEntryHash
120 }
121
122 func (m *pageMetaSource) setCascadeFromMap(frontmatter map[string]any, defaultSitesMatrix sitesmatrix.VectorStore, configuredDimensions *sitesmatrix.ConfiguredDimensions, logger loggers.Logger) error {
123 const (
124 pageMetaKeyCascade = "cascade"
125 )
126
127 // Check for any cascade define on itself.
128 if cv, found := frontmatter[pageMetaKeyCascade]; found {
129 var err error
130 cascade, err := page.DecodeCascadeConfig(cv)
131 if err != nil {
132 return err
133 }
134 if err := cascade.InitConfig(logger, defaultSitesMatrix, configuredDimensions); err != nil {
135 return err
136 }
137
138 m.cascadeCompiled = cascade
139 }
140 return nil
141 }
142
143 var _ contentNodeCascadeProvider = (*pageState)(nil)
144
145 type pageMeta struct {
146 // Shared between all dimensions of this page.
147 *pageMetaSource
148
149 pageConfig *pagemeta.PageConfigLate
150
151 term string // Set for kind == KindTerm.
152 singular string // Set for kind == KindTerm and kind == KindTaxonomy.
153
154 content *cachedContent // The source and the parsed page content.
155
156 datesOriginal pagemeta.Dates // Original dates for rebuilds.
157 }
158
159 func (p *pageState) getCascade() *page.PageMatcherParamsConfigs {
160 return p.m.cascadeCompiled
161 }
162
163 func (m *pageMetaSource) initEarly(h *HugoSites, cascades *page.PageMatcherParamsConfigs) error {
164 if err := m.doInitEarly(h, cascades); err != nil {
165 return m.wrapError(err, h.SourceFs)
166 }
167 return nil
168 }
169
170 func (m *pageMetaSource) doInitEarly(h *HugoSites, cascades *page.PageMatcherParamsConfigs) error {
171 if err := m.initFrontMatter(h); err != nil {
172 return err
173 }
174
175 if m.pageConfigSource.Kind == "" {
176 // Resolve page kind.
177 m.pageConfigSource.Kind = kinds.KindSection
178 if m.pathInfo.Base() == "" {
179 m.pageConfigSource.Kind = kinds.KindHome
180 } else if m.pathInfo.IsBranchBundle() {
181 // A section, taxonomy or term.
182 tc := h.getFirstTaxonomyConfig(m.Path())
183 if !tc.IsZero() {
184 // Either a taxonomy or a term.
185 if tc.pluralTreeKey == m.Path() {
186 m.pageConfigSource.Kind = kinds.KindTaxonomy
187 } else {
188 m.pageConfigSource.Kind = kinds.KindTerm
189 }
190 }
191 } else if m.f != nil {
192 m.pageConfigSource.Kind = kinds.KindPage
193 }
194 }
195
196 sitesMatrixBase := m.sitesMatrixBase
197 if sitesMatrixBase == nil && m.f != nil {
198 sitesMatrixBase = m.f.FileInfo().Meta().SitesMatrix
199 }
200
201 if m.sitesMatrixBaseOnly && sitesMatrixBase == nil {
202 panic("sitesMatrixBaseOnly set, but no base sites matrix")
203 }
204
205 var fim *hugofs.FileMeta
206 if m.f != nil {
207 fim = m.f.FileInfo().Meta()
208 }
209 if err := m.pageConfigSource.CompileEarly(m.pathInfo, cascades, h.Conf, fim, sitesMatrixBase, m.sitesMatrixBaseOnly); err != nil {
210 return err
211 }
212
213 if m.pageConfigSource.Frontmatter != nil {
214 if err := m.setCascadeFromMap(m.pageConfigSource.Frontmatter, m.pageConfigSource.SitesMatrix, h.Conf.ConfiguredDimensions(), h.Log); err != nil {
215 return err
216 }
217 }
218 return nil
219 }
220
221 func (m *pageMetaSource) initFrontMatter(h *HugoSites) error {
222 if m.pathInfo == nil {
223 if err := m.initPathInfo(h); err != nil {
224 return err
225 }
226 }
227
228 if m.pageConfigSource == nil {
229 m.pageConfigSource = &pagemeta.PageConfigEarly{}
230 }
231
232 // Read front matter.
233 if err := m.parseFrontMatter(h, pageSourceIDCounter.Add(1)); err != nil {
234 return err
235 }
236 var ext string
237 if m.f != nil {
238 if !m.f.IsContentAdapter() {
239 ext = m.f.Ext()
240 }
241 }
242
243 if err := m.pageConfigSource.SetMetaPreFromMap(ext, m.pi.frontMatter, h.Log, h.Conf); err != nil {
244 return err
245 }
246
247 // Gate the content format against the security policy. The body of a
248 // content file is treated as untrusted; text/html is denied by default
249 // because Hugo emits it verbatim and that is an XSS sink. This applies
250 // to pages emitted by content adapters too -- the adapter is trusted
251 // but the data it pulls in may not be.
252 if m.f != nil && !m.pageConfigSource.ContentMediaType.IsZero() {
253 if err := h.Deps.ExecHelper.Sec().CheckAllowedContent(m.pageConfigSource.ContentMediaType.Type); err != nil {
254 return err
255 }
256 }
257
258 return nil
259 }
260
261 func (m *pageMetaSource) initPathInfo(h *HugoSites) error {
262 pcfg := m.pageConfigSource
263 if pcfg.Path != "" {
264 s := pcfg.Path
265 // Paths from content adapters should never have any extension.
266 if pcfg.IsFromContentAdapter || !paths.HasExt(s) {
267 var (
268 isBranch bool
269 isBranchSet bool
270 ext string = pcfg.ContentMediaType.FirstSuffix.Suffix
271 )
272 if pcfg.Kind != "" {
273 isBranch = kinds.IsBranch(pcfg.Kind)
274 isBranchSet = true
275 }
276
277 if !pcfg.IsFromContentAdapter {
278 if m.pathInfo != nil {
279 if !isBranchSet {
280 isBranch = m.pathInfo.IsBranchBundle()
281 }
282 if m.pathInfo.Ext() != "" {
283 ext = m.pathInfo.Ext()
284 }
285 } else if m.f != nil {
286 pi := m.f.FileInfo().Meta().PathInfo
287 if !isBranchSet {
288 isBranch = pi.IsBranchBundle()
289 }
290 if pi.Ext() != "" {
291 ext = pi.Ext()
292 }
293 }
294 }
295 if isBranch {
296 s += "/_index." + ext
297 } else {
298 s += "/index." + ext
299 }
300
301 }
302 m.pathInfo = h.Conf.PathParser().Parse(files.ComponentFolderContent, s)
303 } else {
304 if m.f != nil {
305 m.pathInfo = m.f.FileInfo().Meta().PathInfo
306 }
307
308 if m.pathInfo == nil {
309 panic(fmt.Sprintf("missing pathInfo in %v", m))
310 }
311 }
312 return nil
313 }
314
315 func (m *pageMeta) initLate(s *Site) error {
316 var tc viewName
317
318 if m.pageConfigSource.Kind == kinds.KindTerm || m.pageConfigSource.Kind == kinds.KindTaxonomy {
319 if tc.IsZero() {
320 tc = s.pageMap.cfg.getTaxonomyConfig(m.Path())
321 }
322 if tc.IsZero() {
323 return fmt.Errorf("no taxonomy configuration found for %q", m.Path())
324 }
325 m.singular = tc.singular
326
327 if m.pageConfigSource.Kind == kinds.KindTerm {
328 m.term = paths.TrimLeading(strings.TrimPrefix(m.pathInfo.Unnormalized().Base(), "/"+tc.plural))
329 }
330 }
331
332 return nil
333 }
334
335 // bookmark1
336 func (h *HugoSites) newPageMetaSourceFromFile(fi hugofs.FileMetaInfo) (*pageMetaSource, error) {
337 p, err := func() (*pageMetaSource, error) {
338 meta := fi.Meta()
339 openSource := func() (hugio.ReadSeekCloser, error) {
340 r, err := meta.Open()
341 if err != nil {
342 return nil, fmt.Errorf("failed to open file %q: %w", meta.Filename, err)
343 }
344 return r, nil
345 }
346
347 p := &pageMetaSource{
348 f: source.NewFileInfo(fi),
349 pathInfo: fi.Meta().PathInfo,
350 openSource: openSource,
351 }
352
353 return p, nil
354 }()
355 if err != nil {
356 return nil, hugofs.AddFileInfoToError(err, fi, h.SourceFs)
357 }
358
359 return p, err
360 }
361
362 func (h *HugoSites) newPageMetaSourceForContentAdapter(fi hugofs.FileMetaInfo, sitesMatrixBase sitesmatrix.VectorIterator, pc *pagemeta.PageConfigEarly) (*pageMetaSource, error) {
363 p := &pageMetaSource{
364 f: source.NewFileInfo(fi),
365 noFrontMatter: true,
366 pageConfigSource: pc,
367 contentAdapterSourceEntryHash: pc.SourceEntryHash,
368 sitesMatrixBase: sitesMatrixBase,
369 openSource: pc.Content.ValueAsOpenReadSeekCloser(),
370 }
371
372 return p, p.initPathInfo(h)
373 }
374
375 func (s *Site) newPageFromPageMetasource(ms *pageMetaSource, cascades *page.PageMatcherParamsConfigs) (*pageState, error) {
376 m, err := s.newPageMetaFromPageMetasource(ms)
377 if err != nil {
378 return nil, err
379 }
380 p, err := s.newPageFromPageMeta(m, cascades)
381 if err != nil {
382 return nil, err
383 }
384
385 return p, nil
386 }
387
388 func (s *Site) newPageMetaFromPageMetasource(ms *pageMetaSource) (*pageMeta, error) {
389 m := &pageMeta{
390 pageMetaSource: ms,
391 pageConfig: &pagemeta.PageConfigLate{
392 Params: make(hmaps.Params),
393 },
394 }
395 return m, nil
396 }
397
398 // Prepare for a rebuild of the data passed in from front matter.
399 func (m *pageMeta) prepareRebuild() {
400 // Restore orignal date values so we can repeat aggregation.
401 m.pageConfig.Dates = m.datesOriginal
402 }
403
404 func (m *pageMeta) BundleType() string {
405 switch m.pathInfo.Type() {
406 case paths.TypeLeaf:
407 return "leaf"
408 case paths.TypeBranch:
409 return "branch"
410 default:
411 return ""
412 }
413 }
414
415 func (m *pageMeta) Date() time.Time {
416 return m.pageConfig.Dates.Date
417 }
418
419 func (m *pageMeta) PublishDate() time.Time {
420 return m.pageConfig.Dates.PublishDate
421 }
422
423 func (m *pageMeta) Lastmod() time.Time {
424 return m.pageConfig.Dates.Lastmod
425 }
426
427 func (m *pageMeta) ExpiryDate() time.Time {
428 return m.pageConfig.Dates.ExpiryDate
429 }
430
431 func (m *pageMeta) Description() string {
432 return m.pageConfig.Description
433 }
434
435 func (m *pageMeta) Draft() bool {
436 return m.pageConfig.Draft
437 }
438
439 func (m *pageMeta) File() *source.File {
440 return m.f
441 }
442
443 func (m *pageMeta) IsHome() bool {
444 return m.Kind() == kinds.KindHome
445 }
446
447 func (m *pageMeta) Keywords() []string {
448 return m.pageConfig.Keywords
449 }
450
451 func (m *pageMetaSource) Kind() string {
452 return m.pageConfigSource.Kind
453 }
454
455 func (m *pageMeta) Layout() string {
456 return m.pageConfig.Layout
457 }
458
459 func (m *pageMeta) LinkTitle() string {
460 if m.pageConfig.LinkTitle != "" {
461 return m.pageConfig.LinkTitle
462 }
463
464 return m.Title()
465 }
466
467 func (m *pageMeta) Name() string {
468 if m.resourcePath != "" {
469 return m.resourcePath
470 }
471 if m.Kind() == kinds.KindTerm {
472 return m.pathInfo.Unnormalized().BaseNameNoIdentifier()
473 }
474 return m.Title()
475 }
476
477 func (m *pageMeta) IsNode() bool {
478 hugo.Deprecate(".Page.IsNode", "Use .Page.IsBranch or not .Page.IsPage instead.", "v0.163.0")
479 return m.IsBranch()
480 }
481
482 func (m *pageMeta) IsBranch() bool {
483 return kinds.IsBranch(m.Kind())
484 }
485
486 func (m *pageMeta) IsPage() bool {
487 return m.Kind() == kinds.KindPage
488 }
489
490 func (m *pageMeta) Params() hmaps.Params {
491 return m.pageConfig.Params
492 }
493
494 func (m *pageMeta) Path() string {
495 if m.IsHome() {
496 // Base returns an empty string for the home page,
497 // which is correct as the key to the page tree.
498 return "/"
499 }
500 return m.pathInfo.Base()
501 }
502
503 func (m *pageMeta) PathInfo() *paths.Path {
504 return m.pathInfo
505 }
506
507 func (m *pageMeta) IsSection() bool {
508 return m.Kind() == kinds.KindSection
509 }
510
511 func (m *pageMeta) Section() string {
512 return m.pathInfo.Section()
513 }
514
515 func (m *pageMeta) Sitemap() config.SitemapConfig {
516 return m.pageConfig.Sitemap
517 }
518
519 func (m *pageMeta) Title() string {
520 return m.pageConfig.Title
521 }
522
523 const defaultContentType = "page"
524
525 func (m *pageMeta) Type() string {
526 if m.pageConfig.Type != "" {
527 return m.pageConfig.Type
528 }
529
530 if sect := m.Section(); sect != "" {
531 return sect
532 }
533
534 return defaultContentType
535 }
536
537 func (m *pageMeta) Weight() int {
538 return m.pageConfig.Weight
539 }
540
541 func (ps *pageState) setMetaPost(cascades *page.PageMatcherParamsConfigs) error {
542 if ps.m.pageConfigSource.Frontmatter != nil {
543 if ps.m.pageConfigSource.IsFromContentAdapter {
544 ps.m.pageConfig.ContentAdapterData = maps.Clone(ps.m.pageConfigSource.Frontmatter)
545 } else {
546 ps.m.pageConfig.Params = maps.Clone(ps.m.pageConfigSource.Frontmatter)
547 }
548 }
549
550 if ps.m.pageConfig.Params == nil {
551 ps.m.pageConfig.Params = make(hmaps.Params)
552 }
553 if ps.m.pageConfigSource.IsFromContentAdapter && ps.m.pageConfig.ContentAdapterData == nil {
554 ps.m.pageConfig.ContentAdapterData = make(hmaps.Params)
555 }
556
557 // Cascade defined on itself has higher priority than inherited ones.
558 allCascades := hiter.Concat(ps.m.cascadeCompiled.All(), cascades.All())
559
560 for v := range allCascades {
561 if !v.Target.Match(ps.Kind(), ps.Path(), ps.s.Conf.Environment(), ps.s.siteVector) {
562 continue
563 }
564
565 for kk, vv := range v.Params {
566 if _, found := ps.m.pageConfig.Params[kk]; !found {
567 ps.m.pageConfig.Params[kk] = vv
568 }
569 }
570 for kk, vv := range v.Fields {
571 if ps.m.pageConfigSource.IsFromContentAdapter {
572 if _, found := ps.m.pageConfig.ContentAdapterData[kk]; !found {
573 ps.m.pageConfig.ContentAdapterData[kk] = vv
574 }
575 } else {
576 if _, found := ps.m.pageConfig.Params[kk]; !found {
577 ps.m.pageConfig.Params[kk] = vv
578 }
579 }
580 }
581 }
582
583 if err := ps.setMetaPostParams(); err != nil {
584 return err
585 }
586
587 if err := ps.m.applyDefaultValues(ps.s); err != nil {
588 return err
589 }
590
591 // Store away any original values that may be changed from aggregation.
592 ps.m.datesOriginal = ps.m.pageConfig.Dates
593
594 return nil
595 }
596
597 func (ps *pageState) setMetaPostParams() error {
598 pm := ps.m
599 var mtime time.Time
600 var contentBaseName string
601 var isContentAdapter bool
602 if ps.File() != nil {
603 isContentAdapter = ps.File().IsContentAdapter()
604 contentBaseName = ps.File().ContentBaseName()
605 if ps.File().FileInfo() != nil {
606 mtime = ps.File().FileInfo().ModTime()
607 }
608 }
609
610 var gitAuthorDate time.Time
611 if ps.gitInfo != nil {
612 gitAuthorDate = ps.gitInfo.AuthorDate
613 }
614
615 descriptor := &pagemeta.FrontMatterDescriptor{
616 PageConfigEarly: pm.pageConfigSource,
617 PageConfigLate: pm.pageConfig,
618 BaseFilename: contentBaseName,
619 ModTime: mtime,
620 GitAuthorDate: gitAuthorDate,
621 Location: langs.GetLocation(ps.s.Language()),
622 PathOrTitle: ps.pathOrTitle(),
623 }
624
625 if isContentAdapter {
626 if err := pm.pageConfig.Compile(pm.pageConfigSource, ps.s.Log, ps.s.conf.OutputFormats.Config); err != nil {
627 return err
628 }
629 }
630
631 pcfg := pm.pageConfig
632
633 // Handle the date separately
634 // TODO(bep) we need to "do more" in this area so this can be split up and
635 // more easily tested without the Page, but the coupling is strong.
636 err := ps.s.frontmatterHandler.HandleDates(descriptor)
637 if err != nil {
638 ps.s.Log.Errorf("Failed to handle dates for page %q: %s", ps.pathOrTitle(), err)
639 }
640
641 if isContentAdapter {
642 // Done.
643 return nil
644 }
645
646 var sitemapSet bool
647
648 var buildConfig any
649 var isNewBuildKeyword bool
650 if v, ok := pcfg.Params["_build"]; ok {
651 hugo.Deprecate("The \"_build\" front matter key", "Use \"build\" instead. See https://gohugo.io/content-management/build-options.", "0.145.0")
652 buildConfig = v
653 } else {
654 buildConfig = pcfg.Params["build"]
655 isNewBuildKeyword = true
656 }
657 pm.pageConfig.Build, err = pagemeta.DecodeBuildConfig(buildConfig)
658 if err != nil {
659 var msgDetail string
660 if isNewBuildKeyword {
661 msgDetail = `. We renamed the _build keyword to build in Hugo 0.123.0. We recommend putting user defined params in the params section, e.g.:
662 ---
663 title: "My Title"
664 params:
665 build: "My Build"
666 ---
667 ´
668
669 `
670 }
671 return fmt.Errorf("failed to decode build config in front matter: %s%s", err, msgDetail)
672 }
673
674 var draft, published, isCJKLanguage *bool
675 var userParams map[string]any
676 for k, v := range pcfg.Params {
677 loki := strings.ToLower(k)
678
679 if loki == "params" {
680 vv, err := hmaps.ToParamsAndPrepare(v)
681 if err != nil {
682 return fmt.Errorf("front matter field %q must be a map: %w", k, err)
683 }
684 userParams = vv
685 delete(pcfg.Params, k)
686 continue
687 }
688
689 if loki == "published" { // Intentionally undocumented
690 vv, err := cast.ToBoolE(v)
691 if err == nil {
692 published = &vv
693 }
694 // published may also be a date
695 continue
696 }
697
698 if ps.s.frontmatterHandler.IsDateKey(loki) {
699 continue
700 }
701
702 switch loki {
703 case "title":
704 pcfg.Title = cast.ToString(v)
705 pcfg.Params[loki] = pcfg.Title
706 case "linktitle":
707 pcfg.LinkTitle = cast.ToString(v)
708 pcfg.Params[loki] = pcfg.LinkTitle
709 case "summary":
710 pcfg.Summary = cast.ToString(v)
711 pcfg.Params[loki] = pcfg.Summary
712 case "description":
713 pcfg.Description = cast.ToString(v)
714 pcfg.Params[loki] = pcfg.Description
715 case "slug":
716 // Don't start or end with a -
717 pcfg.Slug = strings.Trim(cast.ToString(v), "-")
718 pcfg.Params[loki] = pm.Slug()
719 case "url":
720 url := cast.ToString(v)
721 if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
722 return fmt.Errorf("URLs with protocol (http*) not supported: %q. In page %q", url, ps.pathOrTitle())
723 }
724 pcfg.URL = url
725 pcfg.Params[loki] = url
726 case "type":
727 pcfg.Type = cast.ToString(v)
728 pcfg.Params[loki] = pcfg.Type
729 case "keywords":
730 pcfg.Keywords = cast.ToStringSlice(v)
731 pcfg.Params[loki] = pcfg.Keywords
732 case "headless":
733 // Legacy setting for leaf bundles.
734 // This is since Hugo 0.63 handled in a more general way for all
735 // pages.
736 isHeadless := cast.ToBool(v)
737 pcfg.Params[loki] = isHeadless
738 if isHeadless {
739 pm.pageConfig.Build.List = pagemeta.Never
740 pm.pageConfig.Build.Render = pagemeta.Never
741 }
742 case "outputs":
743 o := cast.ToStringSlice(v)
744 // lower case names:
745 for i, s := range o {
746 o[i] = strings.ToLower(s)
747 }
748 pm.pageConfig.Outputs = o
749 case "draft":
750 draft = new(bool)
751 *draft = cast.ToBool(v)
752 case "layout":
753 pcfg.Layout = cast.ToString(v)
754 pcfg.Params[loki] = pcfg.Layout
755 case "weight":
756 pcfg.Weight = cast.ToInt(v)
757 pcfg.Params[loki] = pcfg.Weight
758 case "aliases":
759 pcfg.Aliases = cast.ToStringSlice(v)
760 for i, alias := range pcfg.Aliases {
761 if strings.HasPrefix(alias, "http://") || strings.HasPrefix(alias, "https://") {
762 return fmt.Errorf("http* aliases not supported: %q", alias)
763 }
764 pcfg.Aliases[i] = filepath.ToSlash(alias)
765 }
766 pcfg.Params[loki] = pcfg.Aliases
767 case "sitemap":
768 pcfg.Sitemap, err = config.DecodeSitemap(ps.s.conf.Sitemap, hmaps.ToStringMap(v))
769 if err != nil {
770 return fmt.Errorf("failed to decode sitemap config in front matter: %s", err)
771 }
772 sitemapSet = true
773 case "iscjklanguage":
774 isCJKLanguage = new(bool)
775 *isCJKLanguage = cast.ToBool(v)
776 case "translationkey":
777 pcfg.TranslationKey = cast.ToString(v)
778 pcfg.Params[loki] = pcfg.TranslationKey
779 case "resources":
780 var resources []map[string]any
781 handled := true
782
783 switch vv := v.(type) {
784 case []map[any]any:
785 for _, vvv := range vv {
786 resources = append(resources, hmaps.ToStringMap(vvv))
787 }
788 case []map[string]any:
789 resources = append(resources, vv...)
790 case []any:
791 for _, vvv := range vv {
792 switch vvvv := vvv.(type) {
793 case map[any]any:
794 resources = append(resources, hmaps.ToStringMap(vvvv))
795 case map[string]any:
796 resources = append(resources, vvvv)
797 }
798 }
799 default:
800 handled = false
801 }
802
803 if handled {
804 pcfg.ResourcesMeta = resources
805 break
806 }
807 fallthrough
808 default:
809 // If not one of the explicit values, store in Params
810 switch vv := v.(type) {
811 case []any:
812 if len(vv) > 0 {
813 allStrings := true
814 for _, vvv := range vv {
815 if _, ok := vvv.(string); !ok {
816 allStrings = false
817 break
818 }
819 }
820 if allStrings {
821 // We need tags, keywords etc. to be []string, not []interface{}.
822 a := make([]string, len(vv))
823 for i, u := range vv {
824 a[i] = cast.ToString(u)
825 }
826 pcfg.Params[loki] = a
827 } else {
828 pcfg.Params[loki] = vv
829 }
830 } else {
831 pcfg.Params[loki] = []string{}
832 }
833
834 default:
835 pcfg.Params[loki] = vv
836 }
837 }
838 }
839
840 for k, v := range userParams {
841 pcfg.Params[strings.ToLower(k)] = v
842 }
843
844 if !sitemapSet {
845 pcfg.Sitemap = ps.s.conf.Sitemap
846 }
847
848 if draft != nil && published != nil {
849 pcfg.Draft = *draft
850 ps.s.Log.Warnf("page %q has both draft and published settings in its frontmatter. Using draft.", ps.File().Filename())
851 } else if draft != nil {
852 pcfg.Draft = *draft
853 } else if published != nil {
854 pcfg.Draft = !*published
855 }
856 pcfg.Params["draft"] = pcfg.Draft
857
858 if isCJKLanguage != nil {
859 pcfg.IsCJKLanguage = *isCJKLanguage
860 } else if ps.s.conf.HasCJKLanguage && ps.m.content.pi.openSource != nil {
861 if cjkRe.Match(ps.m.content.mustSource()) {
862 pcfg.IsCJKLanguage = true
863 } else {
864 pcfg.IsCJKLanguage = false
865 }
866 }
867
868 pcfg.Params["iscjklanguage"] = pcfg.IsCJKLanguage
869
870 if err := pm.pageConfigSource.Init(false); err != nil {
871 return err
872 }
873
874 if err := pcfg.Init(); err != nil {
875 return err
876 }
877
878 if err := pcfg.Compile(pm.pageConfigSource, ps.s.Log, ps.s.conf.OutputFormats.Config); err != nil {
879 return err
880 }
881
882 return nil
883 }
884
885 // shouldList returns whether this page should be included in the list of pages.
886 // global indicates site.Pages etc.
887 func (m *pageMeta) shouldList(global bool) bool {
888 if m.isStandalone() {
889 // Never list 404, sitemap and similar.
890 return false
891 }
892
893 switch m.pageConfig.Build.List {
894 case pagemeta.Always:
895 return true
896 case pagemeta.Never:
897 return false
898 case pagemeta.ListLocally:
899 return !global
900 }
901 return false
902 }
903
904 func (m *pageMeta) shouldListAny() bool {
905 return m.shouldList(true) || m.shouldList(false)
906 }
907
908 func (m *pageMeta) isStandalone() bool {
909 return !m.standaloneOutputFormat.IsZero()
910 }
911
912 func (m *pageMeta) shouldBeCheckedForMenuDefinitions() bool {
913 if !m.shouldList(false) {
914 return false
915 }
916
917 return m.Kind() == kinds.KindHome || m.Kind() == kinds.KindSection || m.Kind() == kinds.KindPage
918 }
919
920 func (m *pageMeta) noRender() bool {
921 return m.pageConfig.Build.Render != pagemeta.Always
922 }
923
924 func (m *pageMeta) noLink() bool {
925 return m.pageConfig.Build.Render == pagemeta.Never
926 }
927
928 func (m *pageMeta) applyDefaultValues(s *Site) error {
929 if m.pageConfig.Build.IsZero() {
930 m.pageConfig.Build, _ = pagemeta.DecodeBuildConfig(nil)
931 }
932
933 if !s.conf.IsKindEnabled(m.Kind()) {
934 (&m.pageConfig.Build).Disable()
935 }
936
937 if m.pageConfigSource.Content.Markup == "" {
938 if m.File() != nil {
939 // Fall back to file extension
940 m.pageConfigSource.Content.Markup = s.ContentSpec.ResolveMarkup(m.File().Ext())
941 }
942 if m.pageConfigSource.Content.Markup == "" {
943 m.pageConfigSource.Content.Markup = "markdown"
944 }
945 }
946
947 if m.pageConfig.Title == "" && m.f == nil {
948 switch m.Kind() {
949 case kinds.KindHome:
950 m.pageConfig.Title = s.Title()
951 case kinds.KindSection:
952 sectionName := m.pathInfo.Unnormalized().BaseNameNoIdentifier()
953 if s.conf.PluralizeListTitles {
954 sectionName = flect.Pluralize(sectionName)
955 }
956 if s.conf.CapitalizeListTitles {
957 sectionName = s.conf.C.CreateTitle(sectionName)
958 }
959 m.pageConfig.Title = sectionName
960 case kinds.KindTerm:
961 if m.term != "" {
962 if s.conf.CapitalizeListTitles {
963 m.pageConfig.Title = s.conf.C.CreateTitle(m.term)
964 } else {
965 m.pageConfig.Title = m.term
966 }
967 } else {
968 panic("term not set")
969 }
970 case kinds.KindTaxonomy:
971 if s.conf.CapitalizeListTitles {
972 m.pageConfig.Title = strings.Replace(s.conf.C.CreateTitle(m.pathInfo.Unnormalized().BaseNameNoIdentifier()), "-", " ", -1)
973 } else {
974 m.pageConfig.Title = strings.Replace(m.pathInfo.Unnormalized().BaseNameNoIdentifier(), "-", " ", -1)
975 }
976 case kinds.KindStatus404:
977 m.pageConfig.Title = "404 Page not found"
978 }
979 }
980
981 return nil
982 }
983
984 func (m *pageMeta) newContentConverter(ps *pageState, markup string) (converter.Converter, error) {
985 if ps == nil {
986 panic("no Page provided")
987 }
988 cp := ps.s.ContentSpec.Converters.Get(markup)
989 if cp == nil {
990 return converter.NopConverter, fmt.Errorf("no content renderer found for markup %q, page: %s", markup, ps.getPageInfoForError())
991 }
992
993 var filename string
994 var path string
995 if m.f != nil {
996 filename = m.f.Filename()
997 path = m.f.Path()
998 } else {
999 path = m.Path()
1000 }
1001
1002 doc := newPageForRenderHook(ps)
1003
1004 documentLookup := func(id uint64) any {
1005 if id == ps.pid {
1006 // This prevents infinite recursion in some cases.
1007 return doc
1008 }
1009 if v, ok := ps.pageOutput.pco.otherOutputs.Get(id); ok {
1010 return v.po.p
1011 }
1012 return nil
1013 }
1014
1015 cpp, err := cp.New(
1016 converter.DocumentContext{
1017 Document: doc,
1018 DocumentLookup: documentLookup,
1019 DocumentID: hashing.XxHashFromStringHexEncoded(ps.Path()),
1020 DocumentName: path,
1021 Filename: filename,
1022 },
1023 )
1024 if err != nil {
1025 return converter.NopConverter, err
1026 }
1027
1028 return cpp, nil
1029 }
1030
1031 // The output formats this page will be rendered to.
1032 func (ps *pageState) outputFormats() output.Formats {
1033 if len(ps.m.pageConfig.ConfiguredOutputFormats) > 0 {
1034 return ps.m.pageConfig.ConfiguredOutputFormats
1035 }
1036 return ps.s.conf.C.KindOutputFormats[ps.Kind()]
1037 }
1038
1039 func (m *pageMeta) Slug() string {
1040 return m.pageConfig.Slug
1041 }
1042
1043 func getParam(m resource.ResourceParamsProvider, key string, stringToLower bool) any {
1044 v := m.Params()[strings.ToLower(key)]
1045
1046 if v == nil {
1047 return nil
1048 }
1049
1050 switch val := v.(type) {
1051 case bool:
1052 return val
1053 case string:
1054 if stringToLower {
1055 return strings.ToLower(val)
1056 }
1057 return val
1058 case int64, int32, int16, int8, int:
1059 return cast.ToInt(v)
1060 case float64, float32:
1061 return cast.ToFloat64(v)
1062 case time.Time:
1063 return val
1064 case []string:
1065 if stringToLower {
1066 return helpers.SliceToLower(val)
1067 }
1068 return v
1069 default:
1070 return v
1071 }
1072 }
1073
1074 func getParamToLower(m resource.ResourceParamsProvider, key string) any {
1075 return getParam(m, key, true)
1076 }