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 view (a layout template) with this Page as
331 // the data context, or, if given, the second argument CONTEXT.
332 Render(ctx context.Context, args ...any) (template.HTML, error)
333 // RenderString renders the first value in args with the content renderer defined
334 // for this Page.
335 // It takes an optional map as a second argument:
336 //
337 // display (“inline”):
338 // - inline or block. If inline (default), surrounding <p></p> on short snippets will be trimmed.
339 // markup (defaults to the Page’s markup)
340 RenderString(ctx context.Context, args ...any) (template.HTML, error)
341 }
342
343 // PageWithoutContent is the Page without any of the content methods.
344 type PageWithoutContent interface {
345 RawContentProvider
346 RenderShortcodesProvider
347 resource.Resource
348 PageMetaProvider
349
350 Param(key any) (any, error)
351 Aliases() []string
352 PageMetaInternalProvider
353
354 resource.LanguageProvider
355
356 // For pages backed by a file.
357 FileProvider
358
359 GitInfoProvider
360
361 // Output formats
362 OutputFormatsProvider
363 AlternativeOutputFormatsProvider
364
365 // Tree navigation
366 ChildCareProvider
367 TreeProvider
368
369 // Horizontal navigation
370 InSectionPositioner
371 PageRenderProvider
372 PaginatorProvider
373 Positioner
374 navigation.PageMenusProvider
375
376 // Page lookups/refs
377 GetPageProvider
378 RefProvider
379
380 resource.TranslationKeyProvider
381 TranslationsProvider
382
383 SiteProvider
384 SitesProvider
385
386 // Helper methods
387 ShortcodeInfoProvider
388 compare.Eqer
389
390 // Scratch returns a Scratch that can be used to store temporary state.
391 // Note that this Scratch gets reset on server rebuilds. See Store() for a variant that survives.
392 // Scratch returns a "scratch pad" that can be used to store state.
393 // Deprecated: From Hugo v0.138.0 this is just an alias for Store.
394 Scratch() *hstore.Scratch
395
396 hstore.StoreProvider
397
398 RelatedKeywordsProvider
399
400 // GetTerms gets the terms of a given taxonomy,
401 // e.g. GetTerms("categories")
402 GetTerms(taxonomy string) Pages
403
404 // HeadingsFiltered returns the headings for this page when a filter is set.
405 // This is currently only triggered with the Related content feature
406 // and the "fragments" type of index.
407 HeadingsFiltered(context.Context) tableofcontents.Headings
408 }
409
410 type SiteDimensionProvider interface {
411 Role() roles.Role
412 }
413
414 // Positioner provides next/prev navigation.
415 type Positioner interface {
416 // Next points up to the next regular page (sorted by Hugo’s default sort).
417 Next() Page
418 // Prev points down to the previous regular page (sorted by Hugo’s default sort).
419 Prev() Page
420 }
421
422 // RawContentProvider provides the raw, unprocessed content of the page.
423 type RawContentProvider interface {
424 // RawContent returns the raw, unprocessed content of the page excluding any front matter.
425 RawContent() string
426 }
427
428 type RenderShortcodesProvider interface {
429 // RenderShortcodes returns RawContent with any shortcodes rendered.
430 RenderShortcodes(context.Context) (template.HTML, error)
431 }
432
433 // RefProvider provides the methods needed to create reflinks to pages.
434 type RefProvider interface {
435 // Ref returns an absolute URl to a page.
436 Ref(argsm map[string]any) (string, error)
437
438 // RefFrom is for internal use only.
439 RefFrom(argsm map[string]any, source any) (string, error)
440
441 // RelRef returns a relative URL to a page.
442 RelRef(argsm map[string]any) (string, error)
443
444 // RelRefFrom is for internal use only.
445 RelRefFrom(argsm map[string]any, source any) (string, error)
446 }
447
448 // RelatedKeywordsProvider allows a Page to be indexed.
449 type RelatedKeywordsProvider interface {
450 // Make it indexable as a related.Document
451 // RelatedKeywords is meant for internal usage only.
452 RelatedKeywords(cfg related.IndexConfig) ([]string, error)
453 }
454
455 // ShortcodeInfoProvider provides info about the shortcodes in a Page.
456 type ShortcodeInfoProvider interface {
457 // HasShortcode return whether the page has a shortcode with the given name.
458 // This method is mainly motivated with the Hugo Docs site's need for a list
459 // of pages with the `todo` shortcode in it.
460 HasShortcode(name string) bool
461 }
462
463 type nopHugoSitesProvider struct{}
464
465 func (nopHugoSitesProvider) Sites() Sites {
466 return nil
467 }
468
469 func (nopHugoSitesProvider) Data() map[string]any {
470 return nil
471 }
472
473 // SitesProvider provide accessors to get sites.
474 type SitesProvider interface {
475 // Sites returns all sites for all dimensions.
476 Sites() Sites
477 }
478
479 // DataProvider provides access to the data directory.
480 type DataProvider interface {
481 Data() map[string]any
482 }
483
484 // SiteProvider provides access to the current site.
485 type SiteProvider interface {
486 Site() Site
487 }
488
489 // TableOfContentsProvider provides the table of contents for a Page.
490 type TableOfContentsProvider interface {
491 // TableOfContents returns the table of contents for the page rendered as HTML.
492 TableOfContents(context.Context) template.HTML
493
494 // Fragments returns the fragments for this page.
495 Fragments(context.Context) *tableofcontents.Fragments
496 }
497
498 // TranslationsProvider provides access to any translations.
499 type TranslationsProvider interface {
500 // IsTranslated returns whether this content file is translated to
501 // other language(s).
502 IsTranslated() bool
503
504 // AllTranslations returns all translations, including the current Page.
505 AllTranslations() Pages
506
507 // Translations returns the translations excluding the current Page.
508 Translations() Pages
509 }
510
511 // TreeProvider provides section tree navigation.
512 type TreeProvider interface {
513 // IsAncestor returns whether the current page is an ancestor of other.
514 // Note that this method is not relevant for taxonomy lists and taxonomy terms pages.
515 IsAncestor(other any) bool
516
517 // CurrentSection returns the page's current section or the page itself if home or a section.
518 // Note that this will return nil for pages that is not regular, home or section pages.
519 CurrentSection() Page
520
521 // IsDescendant returns whether the current page is a descendant of other.
522 // Note that this method is not relevant for taxonomy lists and taxonomy terms pages.
523 IsDescendant(other any) bool
524
525 // FirstSection returns the section on level 1 below home, e.g. "/docs".
526 // For the home page, this will return itself.
527 FirstSection() Page
528
529 // InSection returns whether other is in the current section.
530 // Note that this will always return false for pages that are
531 // not either regular, home or section pages.
532 InSection(other any) bool
533
534 // Parent returns a section's parent section or a page's section.
535 // To get a section's subsections, see Page's Sections method.
536 Parent() Page
537
538 // Ancestors returns the ancestors of each page
539 Ancestors() Pages
540
541 // Sections returns this section's subsections, if any.
542 // Note that for non-sections, this method will always return an empty list.
543 Sections() Pages
544
545 // Page returns a reference to the Page itself, kept here mostly
546 // for legacy reasons.
547 Page() Page
548
549 // Returns a slice of sections (directories if it's a file) to this
550 // Page.
551 SectionsEntries() []string
552
553 // SectionsPath is SectionsEntries joined with a /.
554 SectionsPath() string
555 }
556
557 // SiteVectorProvider provides the dimensions of a Page.
558 type SiteVectorProvider interface {
559 SiteVector() sitesmatrix.Vector
560 }
561
562 // GetSiteVector returns the site vector for a Page,
563 // or the zero value if the Page does not implement SiteVectorProvider.
564 func GetSiteVector(p Page) sitesmatrix.Vector {
565 if sp, ok := p.(SiteVectorProvider); ok {
566 return sp.SiteVector()
567 }
568 return sitesmatrix.Vector{}
569 }
570
571 // LookupSiteVector returns the site vector for a Page and whether it was found.
572 func LookupSiteVector(p Page) (sitesmatrix.Vector, bool) {
573 if sp, ok := p.(SiteVectorProvider); ok {
574 return sp.SiteVector(), true
575 }
576 return sitesmatrix.Vector{}, false
577 }
578
579 // PageWithContext is a Page with a context.Context.
580 type PageWithContext struct {
581 Page
582 Ctx context.Context
583 }
584
585 func (p PageWithContext) Content() (any, error) {
586 return p.Page.Content(p.Ctx)
587 }
588
589 func (p PageWithContext) Plain() string {
590 return p.Page.Plain(p.Ctx)
591 }
592
593 func (p PageWithContext) PlainWords() []string {
594 return p.Page.PlainWords(p.Ctx)
595 }
596
597 func (p PageWithContext) Summary() template.HTML {
598 return p.Page.Summary(p.Ctx)
599 }
600
601 func (p PageWithContext) Truncated() bool {
602 return p.Page.Truncated(p.Ctx)
603 }
604
605 func (p PageWithContext) FuzzyWordCount() int {
606 return p.Page.FuzzyWordCount(p.Ctx)
607 }
608
609 func (p PageWithContext) WordCount() int {
610 return p.Page.WordCount(p.Ctx)
611 }
612
613 func (p PageWithContext) ReadingTime() int {
614 return p.Page.ReadingTime(p.Ctx)
615 }
616
617 func (p PageWithContext) Len() int {
618 return p.Page.Len(p.Ctx)
619 }