Debian Codegraph @

resources/page/page.go

raw
1 // Copyright 2019 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 page contains the core interfaces and types for the Page resource,
15 // a core component in Hugo.
16 package page
17
18 import (
19 "context"
20 "fmt"
21 "html/template"
22
23 "github.com/gohugoio/hugo/hugolib/roles"
24 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
25 "github.com/gohugoio/hugo/markup/converter"
26 "github.com/gohugoio/hugo/markup/tableofcontents"
27
28 "github.com/gohugoio/hugo/config"
29
30 "github.com/gohugoio/hugo/common/hstore"
31 "github.com/gohugoio/hugo/common/paths"
32 "github.com/gohugoio/hugo/compare"
33
34 "github.com/gohugoio/hugo/navigation"
35 "github.com/gohugoio/hugo/related"
36 "github.com/gohugoio/hugo/resources/resource"
37 "github.com/gohugoio/hugo/source"
38 )
39
40 // Clear clears any global package state.
41 func Clear() error {
42 spc.clear()
43 return nil
44 }
45
46 // AlternativeOutputFormatsProvider provides alternative output formats for a
47 // Page.
48 type AlternativeOutputFormatsProvider interface {
49 // AlternativeOutputFormats gives the alternative output formats for the
50 // current output.
51 // Note that we use the term "alternative" and not "alternate" here, as it
52 // does not necessarily replace the other format, it is an alternative representation.
53 AlternativeOutputFormats() OutputFormats
54 }
55
56 // ChildCareProvider provides accessors to child resources.
57 type ChildCareProvider interface {
58 // Pages returns a list of pages of all kinds.
59 Pages() Pages
60
61 // RegularPages returns a list of pages of kind 'Page'.
62 RegularPages() Pages
63
64 // RegularPagesRecursive returns all regular pages below the current
65 // section.
66 RegularPagesRecursive() Pages
67
68 resource.ResourcesProvider
69 }
70
71 type MarkupProvider interface {
72 Markup(opts ...any) Markup
73 }
74
75 // ContentProvider provides the content related values for a Page.
76 type ContentProvider interface {
77 Content(context.Context) (any, error)
78
79 // ContentWithoutSummary returns the Page Content stripped of the summary.
80 ContentWithoutSummary(ctx context.Context) (template.HTML, error)
81
82 // Plain returns the Page Content stripped of HTML markup.
83 Plain(context.Context) string
84
85 // PlainWords returns a string slice from splitting Plain using https://pkg.go.dev/strings#Fields.
86 PlainWords(context.Context) []string
87
88 // Summary returns a generated summary of the content.
89 // The breakpoint can be set manually by inserting a summary separator in the source file.
90 Summary(context.Context) template.HTML
91
92 // Truncated returns whether the Summary is truncated or not.
93 Truncated(context.Context) bool
94
95 // FuzzyWordCount returns the approximate number of words in the content.
96 FuzzyWordCount(context.Context) int
97
98 // WordCount returns the number of words in the content.
99 WordCount(context.Context) int
100
101 // ReadingTime returns the reading time based on the length of plain text.
102 ReadingTime(context.Context) int
103
104 // Len returns the length of the content.
105 // This is for internal use only.
106 Len(context.Context) int
107 }
108
109 // ContentRenderer provides the content rendering methods for some content.
110 type ContentRenderer interface {
111 // ParseAndRenderContent renders the given content.
112 // For internal use only.
113 ParseAndRenderContent(ctx context.Context, content []byte, enableTOC bool) (converter.ResultRender, error)
114 // For internal use only.
115 ParseContent(ctx context.Context, content []byte) (converter.ResultParse, bool, error)
116 // For internal use only.
117 RenderContent(ctx context.Context, content []byte, sourceInfo, doc any) (converter.ResultRender, bool, error)
118 }
119
120 // FileProvider provides the source file.
121 type FileProvider interface {
122 // File returns the source file for this Page,
123 // or a zero File if this Page is not backed by a file.
124 File() *source.File
125 }
126
127 // GetPageProvider provides the GetPage method.
128 type GetPageProvider interface {
129 // GetPage looks up a page for the given ref.
130 // {{ with .GetPage "blog" }}{{ .Title }}{{ end }}
131 //
132 // This will return nil when no page could be found, and will return
133 // an error if the ref is ambiguous.
134 GetPage(ref string) (Page, error)
135 }
136
137 // GitInfoProvider provides Git info.
138 type GitInfoProvider interface {
139 // GitInfo returns the Git info for this object.
140 GitInfo() *source.GitInfo
141 // CodeOwners returns the code owners for this object.
142 CodeOwners() []string
143 }
144
145 // InSectionPositioner provides section navigation.
146 type InSectionPositioner interface {
147 // NextInSection returns the next page in the same section.
148 NextInSection() Page
149 // PrevInSection returns the previous page in the same section.
150 PrevInSection() Page
151 }
152
153 // RelatedDocsHandlerProvider is considered an internal interface.
154 type RelatedDocsHandlerProvider interface {
155 // GetInternalRelatedDocsHandler is for internal use only.
156 GetInternalRelatedDocsHandler() *RelatedDocsHandler
157 }
158
159 // OutputFormatsProvider provides the OutputFormats of a Page.
160 type OutputFormatsProvider interface {
161 // OutputFormats returns the OutputFormats for this Page.
162 OutputFormats() OutputFormats
163 }
164
165 // PageProvider provides access to a Page.
166 // Implemented by shortcodes and others.
167 type PageProvider interface {
168 Page() Page
169 }
170
171 // Page is the core interface in Hugo and what you get as the top level data context in your templates.
172 type Page interface {
173 MarkupProvider
174 ContentProvider
175 TableOfContentsProvider
176 PageWithoutContent
177 fmt.Stringer
178 }
179
180 type PageFragment interface {
181 resource.ResourceLinksProvider
182 resource.ResourceNameTitleProvider
183 }
184
185 type PageMetaResource interface {
186 PageMetaProvider
187 resource.Resource
188 }
189
190 type PageMetaLanguageResource interface {
191 PageMetaResource
192 resource.LanguageProvider
193 }
194
195 // PageMetaProvider provides page metadata, typically provided via front matter.
196 type PageMetaProvider interface {
197 // The 4 page dates
198 resource.Dated
199
200 // BundleType returns the bundle type: `leaf`, `branch` or an empty string.
201 BundleType() string
202
203 // A configured description.
204 Description() string
205
206 // Whether this is a draft. Will only be true if run with the --buildDrafts (-D) flag.
207 Draft() bool
208
209 // IsHome returns whether this is the home page.
210 IsHome() bool
211
212 // Configured keywords.
213 Keywords() []string
214
215 // The Page Kind. One of page, home, section, taxonomy, term.
216 Kind() string
217
218 // The configured layout to use to render this page. Typically set in front matter.
219 Layout() string
220
221 // The title used for links.
222 LinkTitle() string
223
224 // IsNode returns whether this is a branch node (e.g. a section).
225 //
226 // Deprecated: Use IsBranch or "not IsPage" instead.
227 IsNode() bool
228
229 // IsBranch returns whether this is a branch node, i.e. a node that
230 // can have descendants (home, section, taxonomy or term).
231 IsBranch() bool
232
233 // IsPage returns whether this is a regular content
234 IsPage() bool
235
236 // Path gets the relative path, including file name and extension if relevant,
237 // to the source of this Page. It will be relative to any content root.
238 Path() string
239
240 // The slug, typically defined in front matter.
241 Slug() string
242
243 // IsSection returns whether this is a section
244 IsSection() bool
245
246 // Section returns the first path element below the content root.
247 Section() string
248
249 // Sitemap returns the sitemap configuration for this page.
250 // This is for internal use only.
251 Sitemap() config.SitemapConfig
252
253 // Type is a discriminator used to select layouts etc. It is typically set
254 // in front matter, but will fall back to the root section.
255 Type() string
256
257 // The configured weight, used as the first sort value in the default
258 // page sort if non-zero.
259 Weight() int
260 }
261
262 // NamedPageMetaValue returns a named metadata value from a PageMetaResource.
263 // This is currently only used to generate keywords for related content.
264 // If nameLower is not one of the metadata interface methods, we
265 // look in Params.
266 func NamedPageMetaValue(p PageMetaLanguageResource, nameLower string) (any, bool, error) {
267 var (
268 v any
269 err error
270 )
271
272 switch nameLower {
273 case "kind":
274 v = p.Kind()
275 case "bundletype":
276 v = p.BundleType()
277 case "mediatype":
278 v = p.MediaType()
279 case "section":
280 v = p.Section()
281 case "lang":
282 v = p.Lang()
283 case "name":
284 v = p.Name()
285 case "keywords":
286 v = p.Keywords()
287 case "description":
288 v = p.Description()
289 case "title":
290 v = p.Title()
291 case "linktitle":
292 v = p.LinkTitle()
293 case "slug":
294 v = p.Slug()
295 case "date":
296 v = p.Date()
297 case "publishdate":
298 v = p.PublishDate()
299 case "expirydate":
300 v = p.ExpiryDate()
301 case "lastmod":
302 v = p.Lastmod()
303 case "draft":
304 v = p.Draft()
305 case "type":
306 v = p.Type()
307 case "layout":
308 v = p.Layout()
309 case "weight":
310 v = p.Weight()
311 default:
312 // Try params.
313 v, err = resource.Param(p, nil, nameLower)
314 if v == nil {
315 return nil, false, nil
316 }
317 }
318
319 return v, err == nil, err
320 }
321
322 // PageMetaInternalProvider provides internal page metadata.
323 type PageMetaInternalProvider interface {
324 // This is for internal use only.
325 PathInfo() *paths.Path
326 }
327
328 // PageRenderProvider provides a way for a Page to render content.
329 type PageRenderProvider interface {
330 // Render renders the given layout with this Page as context.
331 Render(ctx context.Context, layout ...string) (template.HTML, error)
332 // RenderString renders the first value in args with the content renderer defined
333 // for this Page.
334 // It takes an optional map as a second argument:
335 //
336 // display (“inline”):
337 // - inline or block. If inline (default), surrounding <p></p> on short snippets will be trimmed.
338 // markup (defaults to the Page’s markup)
339 RenderString(ctx context.Context, args ...any) (template.HTML, error)
340 }
341
342 // PageWithoutContent is the Page without any of the content methods.
343 type PageWithoutContent interface {
344 RawContentProvider
345 RenderShortcodesProvider
346 resource.Resource
347 PageMetaProvider
348
349 Param(key any) (any, error)
350 Aliases() []string
351 PageMetaInternalProvider
352
353 resource.LanguageProvider
354
355 // For pages backed by a file.
356 FileProvider
357
358 GitInfoProvider
359
360 // Output formats
361 OutputFormatsProvider
362 AlternativeOutputFormatsProvider
363
364 // Tree navigation
365 ChildCareProvider
366 TreeProvider
367
368 // Horizontal navigation
369 InSectionPositioner
370 PageRenderProvider
371 PaginatorProvider
372 Positioner
373 navigation.PageMenusProvider
374
375 // Page lookups/refs
376 GetPageProvider
377 RefProvider
378
379 resource.TranslationKeyProvider
380 TranslationsProvider
381
382 SiteProvider
383 SitesProvider
384
385 // Helper methods
386 ShortcodeInfoProvider
387 compare.Eqer
388
389 // Scratch returns a Scratch that can be used to store temporary state.
390 // Note that this Scratch gets reset on server rebuilds. See Store() for a variant that survives.
391 // Scratch returns a "scratch pad" that can be used to store state.
392 // Deprecated: From Hugo v0.138.0 this is just an alias for Store.
393 Scratch() *hstore.Scratch
394
395 hstore.StoreProvider
396
397 RelatedKeywordsProvider
398
399 // GetTerms gets the terms of a given taxonomy,
400 // e.g. GetTerms("categories")
401 GetTerms(taxonomy string) Pages
402
403 // HeadingsFiltered returns the headings for this page when a filter is set.
404 // This is currently only triggered with the Related content feature
405 // and the "fragments" type of index.
406 HeadingsFiltered(context.Context) tableofcontents.Headings
407 }
408
409 type SiteDimensionProvider interface {
410 Role() roles.Role
411 }
412
413 // Positioner provides next/prev navigation.
414 type Positioner interface {
415 // Next points up to the next regular page (sorted by Hugo’s default sort).
416 Next() Page
417 // Prev points down to the previous regular page (sorted by Hugo’s default sort).
418 Prev() Page
419 }
420
421 // RawContentProvider provides the raw, unprocessed content of the page.
422 type RawContentProvider interface {
423 // RawContent returns the raw, unprocessed content of the page excluding any front matter.
424 RawContent() string
425 }
426
427 type RenderShortcodesProvider interface {
428 // RenderShortcodes returns RawContent with any shortcodes rendered.
429 RenderShortcodes(context.Context) (template.HTML, error)
430 }
431
432 // RefProvider provides the methods needed to create reflinks to pages.
433 type RefProvider interface {
434 // Ref returns an absolute URl to a page.
435 Ref(argsm map[string]any) (string, error)
436
437 // RefFrom is for internal use only.
438 RefFrom(argsm map[string]any, source any) (string, error)
439
440 // RelRef returns a relative URL to a page.
441 RelRef(argsm map[string]any) (string, error)
442
443 // RelRefFrom is for internal use only.
444 RelRefFrom(argsm map[string]any, source any) (string, error)
445 }
446
447 // RelatedKeywordsProvider allows a Page to be indexed.
448 type RelatedKeywordsProvider interface {
449 // Make it indexable as a related.Document
450 // RelatedKeywords is meant for internal usage only.
451 RelatedKeywords(cfg related.IndexConfig) ([]related.Keyword, error)
452 }
453
454 // ShortcodeInfoProvider provides info about the shortcodes in a Page.
455 type ShortcodeInfoProvider interface {
456 // HasShortcode return whether the page has a shortcode with the given name.
457 // This method is mainly motivated with the Hugo Docs site's need for a list
458 // of pages with the `todo` shortcode in it.
459 HasShortcode(name string) bool
460 }
461
462 type nopHugoSitesProvider struct{}
463
464 func (nopHugoSitesProvider) Sites() Sites {
465 return nil
466 }
467
468 func (nopHugoSitesProvider) Data() map[string]any {
469 return nil
470 }
471
472 // SitesProvider provide accessors to get sites.
473 type SitesProvider interface {
474 // Sites returns all sites for all dimensions.
475 Sites() Sites
476 }
477
478 // DataProvider provides access to the data directory.
479 type DataProvider interface {
480 Data() map[string]any
481 }
482
483 // SiteProvider provides access to the current site.
484 type SiteProvider interface {
485 Site() Site
486 }
487
488 // TableOfContentsProvider provides the table of contents for a Page.
489 type TableOfContentsProvider interface {
490 // TableOfContents returns the table of contents for the page rendered as HTML.
491 TableOfContents(context.Context) template.HTML
492
493 // Fragments returns the fragments for this page.
494 Fragments(context.Context) *tableofcontents.Fragments
495 }
496
497 // TranslationsProvider provides access to any translations.
498 type TranslationsProvider interface {
499 // IsTranslated returns whether this content file is translated to
500 // other language(s).
501 IsTranslated() bool
502
503 // AllTranslations returns all translations, including the current Page.
504 AllTranslations() Pages
505
506 // Translations returns the translations excluding the current Page.
507 Translations() Pages
508 }
509
510 // TreeProvider provides section tree navigation.
511 type TreeProvider interface {
512 // IsAncestor returns whether the current page is an ancestor of other.
513 // Note that this method is not relevant for taxonomy lists and taxonomy terms pages.
514 IsAncestor(other any) bool
515
516 // CurrentSection returns the page's current section or the page itself if home or a section.
517 // Note that this will return nil for pages that is not regular, home or section pages.
518 CurrentSection() Page
519
520 // IsDescendant returns whether the current page is a descendant of other.
521 // Note that this method is not relevant for taxonomy lists and taxonomy terms pages.
522 IsDescendant(other any) bool
523
524 // FirstSection returns the section on level 1 below home, e.g. "/docs".
525 // For the home page, this will return itself.
526 FirstSection() Page
527
528 // InSection returns whether other is in the current section.
529 // Note that this will always return false for pages that are
530 // not either regular, home or section pages.
531 InSection(other any) bool
532
533 // Parent returns a section's parent section or a page's section.
534 // To get a section's subsections, see Page's Sections method.
535 Parent() Page
536
537 // Ancestors returns the ancestors of each page
538 Ancestors() Pages
539
540 // Sections returns this section's subsections, if any.
541 // Note that for non-sections, this method will always return an empty list.
542 Sections() Pages
543
544 // Page returns a reference to the Page itself, kept here mostly
545 // for legacy reasons.
546 Page() Page
547
548 // Returns a slice of sections (directories if it's a file) to this
549 // Page.
550 SectionsEntries() []string
551
552 // SectionsPath is SectionsEntries joined with a /.
553 SectionsPath() string
554 }
555
556 // SiteVectorProvider provides the dimensions of a Page.
557 type SiteVectorProvider interface {
558 SiteVector() sitesmatrix.Vector
559 }
560
561 // GetSiteVector returns the site vector for a Page,
562 // or the zero value if the Page does not implement SiteVectorProvider.
563 func GetSiteVector(p Page) sitesmatrix.Vector {
564 if sp, ok := p.(SiteVectorProvider); ok {
565 return sp.SiteVector()
566 }
567 return sitesmatrix.Vector{}
568 }
569
570 // LookupSiteVector returns the site vector for a Page and whether it was found.
571 func LookupSiteVector(p Page) (sitesmatrix.Vector, bool) {
572 if sp, ok := p.(SiteVectorProvider); ok {
573 return sp.SiteVector(), true
574 }
575 return sitesmatrix.Vector{}, false
576 }
577
578 // PageWithContext is a Page with a context.Context.
579 type PageWithContext struct {
580 Page
581 Ctx context.Context
582 }
583
584 func (p PageWithContext) Content() (any, error) {
585 return p.Page.Content(p.Ctx)
586 }
587
588 func (p PageWithContext) Plain() string {
589 return p.Page.Plain(p.Ctx)
590 }
591
592 func (p PageWithContext) PlainWords() []string {
593 return p.Page.PlainWords(p.Ctx)
594 }
595
596 func (p PageWithContext) Summary() template.HTML {
597 return p.Page.Summary(p.Ctx)
598 }
599
600 func (p PageWithContext) Truncated() bool {
601 return p.Page.Truncated(p.Ctx)
602 }
603
604 func (p PageWithContext) FuzzyWordCount() int {
605 return p.Page.FuzzyWordCount(p.Ctx)
606 }
607
608 func (p PageWithContext) WordCount() int {
609 return p.Page.WordCount(p.Ctx)
610 }
611
612 func (p PageWithContext) ReadingTime() int {
613 return p.Page.ReadingTime(p.Ctx)
614 }
615
616 func (p PageWithContext) Len() int {
617 return p.Page.Len(p.Ctx)
618 }