template

package
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 28, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatDate

func FormatDate(layout string, t time.Time) string

FormatDate formats a specific time with the given layout.

func FuncMap

func FuncMap(baseURL string) template.FuncMap

FuncMap returns all custom template functions needed to render the site.

func LinkPageRelationships

func LinkPageRelationships(ctx *Context, p *content.Page, lookup map[*content.Page]*Context)

LinkPageRelationships fills in Pages/RegularPages/RegularPagesRecursive on a Context after all contexts are built, via a page→context lookup.

func LoadAllTemplates

func LoadAllTemplates(sourceDir, baseURL string, themeMgr ...*theme.Manager) (*template.Template, error)

LoadAllTemplates is a convenience function that loads all templates. It accepts an optional theme.Manager to support theme plugin templates. When themeMgr is provided, the loader uses NewLoaderWithTheme; otherwise it falls back to the legacy directory-based theme detection and NewLoader.

func PopulateSitePages

func PopulateSitePages(siteCtx *SiteContext, site *content.Site, lookup map[*content.Page]*Context)

all page contexts exist.

func RssLastBuildDate

func RssLastBuildDate(ctx interface{}) string

RssLastBuildDate returns the RSS-formatted most-recent Lastmod among the context's RegularPages, or "" when RegularPages is empty. The empty string matches Hugo's output for "empty" tags (those whose only pages are hidden), where Hugo emits <lastBuildDate/> rather than a zero-time formatted date.

func SetActiveTemplate

func SetActiveTemplate(t *template.Template)

SetActiveTemplate updates the active template reference used by the partial closure.

func SetI18nBundle

func SetI18nBundle(b I18nBundle)

SetI18nBundle installs the bundle used by the i18n template function.

func SetPaginator

func SetPaginator(c *Context, p *PaginatorContext)

SetPaginator overrides the cached paginator (used by pagination page generation).

func ToURLize

func ToURLize(s string) string

ToURLize mirrors Hugo's urlize behavior:

  • lowercase ASCII letters
  • spaces become "-"
  • CJK and other Unicode characters are URL-encoded with UPPERCASE hex (matching Hugo's urlize output, e.g. 书稿 → %E4%B9%A6%E7%A8%BF)
  • other special chars (parens, etc.) are URL-encoded with UPPERCASE hex

Note: this differs from html/template's auto-URL-escaping (lowercase hex) used when templates emit raw CJK in href/src attributes.

Types

type AuthorContext

type AuthorContext struct {
	Name string
}

type CompareFunc

type CompareFunc func(a, b string) int

CompareFunc is a string comparison function used by SortDefault for the Title tie-break layer. Returns <0 if a<b, 0 if equal, >0 if a>b.

type Context

type Context struct {
	// Page fields - accessed as .Title, .Content, etc.
	Title         string
	Date          time.Time
	Lastmod       time.Time
	Draft         bool
	Hidden        bool
	Type          string
	Slug          string
	Tags          []string
	Keywords      []string
	Description   string
	Author        string
	Image         string
	FeaturedImage string
	Section       string
	Kind          string
	Weight        int
	WordCount     int
	ReadingTime   int

	Content      template.HTML
	Summary      template.HTML
	Plain        string
	RelPermalink string
	Permalink    string

	Params  map[string]interface{}
	Build   config.BuildConfig
	Cascade config.CascadeConfig
	Sitemap config.SitemapPageConfig

	File                  *FileInfo
	Site                  *SiteContext
	Pages                 PageSlice
	RegularPages          PageSlice
	RegularPagesRecursive PageSlice
	Parent                *Context

	Paginated bool // true if this context is itself a paginated result

	// Output formats
	OutputFormats *PageOutputFormats

	// Data from data files (or a DataAccessor for taxonomy pages)
	Data interface{}

	// Scratch for template-scoped variables
	Scratch *Scratch

	// Taxonomy data: term listing (for /tags/) and current term info (for /tags/X/)
	DataTerms  []TermSummaryExternal
	DataPlural string

	// For taxonomy pages
	Data_ *TaxonomyDataContext

	// i18n fields (populated by NewContext from page.Language + cfg.Languages)
	// Language is the current page's language code (e.g. "zh-cn", "en").
	// Empty string means default language (backward-compat with single-lang builds).
	PageLanguage string
	// IsDefaultLanguage is true when PageLanguage matches cfg.DefaultLanguageCode.
	IsDefaultLanguage bool
	// LanguagePrefix is the URL prefix for the current language ("" or "/en").
	LanguagePrefix string
	// TranslationLinks lists all configured language variants for this page,
	// including the current language. Empty when single-language build.
	TranslationLinks []TranslationLink
	// contains filtered or unexported fields
}

Context is the data object passed to every template. It mirrors Hugo's page context: .Title, .Content, .Site, .Params, etc.

func AsCtx

func AsCtx(v interface{}) *Context

AsCtx is the exported form of asCtx.

func NewContext

func NewContext(p *content.Page, siteCtx *SiteContext, cfg *config.Config) *Context

NewContext creates a template context from a Page and a shared SiteContext. The site context must be built once via NewSiteContext() and passed in.

func (c *Context) AllTranslationLinks() []TranslationLink

AllTranslationLinks returns all language variants of the current page, INCLUDING the current language (marked IsCurrent=true). Used by hreflang template function to emit all alternate links.

func (*Context) Format

func (c *Context) Format(layout string) string

Format formats the date with Go's time format.

func (*Context) IsHome

func (c *Context) IsHome() bool

func (*Context) IsPage

func (c *Context) IsPage() bool

IsPage returns true if this is a regular page.

func (*Context) IsSection

func (c *Context) IsSection() bool

IsSection returns true if this is a section page.

func (*Context) IsTranslated

func (c *Context) IsTranslated() bool

IsTranslated returns true when the page has at least one other-language variant. Powered by ctx.TranslationLinks (populated by NewContext from cfg.Languages). Returns false for single-language builds.

func (*Context) Paginate

func (c *Context) Paginate(args ...interface{}) *PaginatorContext

pages of cfg.Paginate size and returns the first pager as PaginatorContext. Hugo variadic: .Paginate, .Paginate pages, .Paginate pages size. If a paginator is already cached (e.g., for /page/N/ rendering), returns it.

func (*Context) Paginator

func (c *Context) Paginator() *PaginatorContext

Paginator mirrors Hugo's .Paginator - auto-paginates this section's pages. Returns the first pager; subsequent pagers are linked via Next.

func (*Context) PublishDate

func (c *Context) PublishDate() time.Time

PublishDate returns the page's publication date (Hugo compatibility).

func (*Context) TermsData

func (c *Context) TermsData() *DataAccessor

TermsData returns a DataAccessor for the templates' `.Data.Terms` access.

func (*Context) Translations

func (c *Context) Translations() PageSlice

Translations returns other-language variants of the current page, excluding the current language itself. Returns empty slice for single-language builds or when no other-language variants exist.

type DataAccessor

type DataAccessor struct {
	Terms  TermsList
	Plural string
	Pages  PageSlice
}

DataAccessor wraps DataTerms for `.Data.Terms.ByCount` template access.

func (*DataAccessor) GroupByDate

func (d *DataAccessor) GroupByDate(layout string) []DateGroup

GroupByDate on DataAccessor.Pages mirrors PageSlice.GroupByDate.

type DateGroup

type DateGroup struct {
	Key   string
	Pages PageSlice
}

DateGroup is a Hugo-compatible group of pages sharing a date key.

type FileInfo

type FileInfo struct {
	Path         string
	Dir          string
	BaseFileName string
}

FileInfo mirrors Hugo's .File object.

type I18nBundle

type I18nBundle interface {
	Translate(key string, args ...interface{}) string
}

I18nBundle is the minimal interface the template package needs from an i18n bundle.

type LanguageContext

type LanguageContext struct {
	LanguageCode      string
	LanguageName      string
	LanguageDirection string
}

LanguageContext mirrors Hugo's .Site.Language object.

type Loader

type Loader struct {
	// contains filtered or unexported fields
}

Loader discovers and loads template files from a theme and local layouts.

func NewLoader

func NewLoader(sourceDir, themeName string, funcMap template.FuncMap) *Loader

NewLoader creates a template loader.

func NewLoaderWithTheme added in v0.7.0

func NewLoaderWithTheme(sourceDir, layoutsDir string, funcMap template.FuncMap, themeMgr *theme.Manager) *Loader

NewLoaderWithTheme creates a template loader with theme plugin support. Theme plugin templates are loaded first, then theme directory, then layouts/ directory (highest priority). This mirrors the traditional override chain: layouts/ overrides theme dir overrides theme plugin.

func (*Loader) LoadAll

func (l *Loader) LoadAll() (*template.Template, error)

LoadAll loads all templates and returns a ready-to-execute *template.Template.

type Map

type Map map[string]interface{}

Map is a generic string-keyed map.

type MediaType

type MediaType struct {
	Type string
}

MediaType is a simple media type wrapper supporting .Type in templates.

type OutputFormat

type OutputFormat struct {
	Name      string
	MediaType string
	BaseName  string
	Rel       string
}

type OutputFormatsContext

type OutputFormatsContext struct {
	Formats []OutputFormat
}

OutputFormatsContext for .Site.OutputFormats.

type PageOutputFormat

type PageOutputFormat struct {
	Name         string
	Rel          string
	MediaType    MediaType
	Permalink    string
	RelPermalink string
}

PageOutputFormat is a single output format for a page, with a computed Permalink.

type PageOutputFormats

type PageOutputFormats struct {
	// contains filtered or unexported fields
}

PageOutputFormats wraps output formats for a single page.

func DefaultPageOutputFormats

func DefaultPageOutputFormats(permalink, relPermalink string) *PageOutputFormats

DefaultPageOutputFormats returns a reasonable default for an HTML page.

func HTMLOnlyOutputFormats

func HTMLOnlyOutputFormats(permalink, relPermalink string) *PageOutputFormats

HTMLOnlyOutputFormats returns output formats with just HTML (no RSS). Used for pages like 404 that shouldn't have an RSS feed.

func (*PageOutputFormats) Get

type PageSlice

type PageSlice []interface{}

PageSlice is a sortable, chainable slice of page contexts. Implemented as []interface{} so it is interchangeable with the result of Hugo's slice() function in Go templates (which returns []interface{}).

func (PageSlice) ByDate

func (p PageSlice) ByDate() PageSlice

ByDate sorts pages by Date ascending and returns the result.

func (PageSlice) ByLastmod

func (p PageSlice) ByLastmod() PageSlice

ByLastmod sorts pages by Lastmod ascending and returns the result.

func (PageSlice) ByPublishDate

func (p PageSlice) ByPublishDate() PageSlice

ByPublishDate sorts pages by PublishDate ascending.

func (PageSlice) First

func (p PageSlice) First() *Context

First returns the first page, or a safe default Context if empty. Returning a non-nil value avoids template nil-pointer panics when callers chain methods like .First.Lastmod.

func (PageSlice) GroupByDate

func (p PageSlice) GroupByDate(layout string) []DateGroup

GroupByDate groups pages by year, returning groups in descending order. Within each group, pages are sorted by Date desc with Title desc (via the site collator) as tiebreaker — matching Hugo's observed behavior. Hugo's GroupByDate groups pages by the formatted date key (reverse chronological order across groups), and within each group applies a Date desc → Title desc → Path desc ordering (effectively the reverse of DefaultPageSort's tiebreakers, since GroupByDate sorts by Date desc as primary key).

For zhurongshuo, two posts can share the exact same Date timestamp (e.g. post 0801 and 0802 both at 2021-08-08T12:27:45+08:00). Hugo's tiebreaker for these is the reverse of the site collator's Title comparison.

func (PageSlice) Len

func (p PageSlice) Len() int

Len returns the number of pages.

func (PageSlice) Reverse

func (p PageSlice) Reverse() PageSlice

Reverse returns the slice in reverse order.

func (PageSlice) SortDefault

func (p PageSlice) SortDefault(coll CompareFunc)

SortDefault sorts the slice in-place using Hugo's DefaultPageSort:

  • Weight (0 sorts last; otherwise ascending)
  • Date desc
  • Linkable Title asc (uses Title when LinkTitle empty)
  • RelPermalink asc (byte-level)

The collator is required for the Title tie-break layer. Callers should construct it once per build via i18n.BuildCollator(langCode) and reuse.

type PaginatorContext

type PaginatorContext struct {
	PageNumber int
	URL        string
	Pages      PageSlice
	HasPrev    bool
	HasNext    bool
	Prev       *PaginatorContext
	Next       *PaginatorContext
	First      *PaginatorContext
	Last       *PaginatorContext
	PagerSize  int
	TotalPages int
}

PaginatorContext mirrors Hugo's .Paginator object.

type Renderer

type Renderer struct {
	// contains filtered or unexported fields
}

Renderer handles executing templates with context data. It keeps a "factory" template (never executed) and clones it for each render, so context-specific functions like `site` can be injected per-call.

func NewRenderer

func NewRenderer(tmpl *template.Template, funcMap template.FuncMap) *Renderer

NewRenderer creates a new template renderer.

func (*Renderer) Render

func (r *Renderer) Render(templateName string, ctx *Context) (string, error)

Render executes a named template with the given context. For each render, it clones the factory template and injects the `site` function returning the current Site context. The `partial` and `partialCached` functions are also overridden on the clone to close over the cloned template directly, avoiding a global variable race.

type Scratch

type Scratch struct {
	// contains filtered or unexported fields
}

Scratch provides template-scoped mutable storage.

func NewScratch

func NewScratch() *Scratch

func (*Scratch) Add

func (s *Scratch) Add(key string, value interface{}) interface{}

func (*Scratch) Get

func (s *Scratch) Get(key string) interface{}

func (*Scratch) Set

func (s *Scratch) Set(key string, value interface{}) interface{}

type SiteContext

type SiteContext struct {
	Title        string
	BaseURL      string
	Language     *LanguageContext
	Params       map[string]interface{}
	Menus        map[string][]config.MenuItem
	Pages        PageSlice
	RegularPages PageSlice
	Data         map[string]interface{}
	Taxonomies   map[string]TaxonomyContext
	Config       *config.Config
	LanguageCode string
	Author       *AuthorContext

	// Copyright string (Hugo compatibility)
	Copyright string

	// Output formats
	OutputFormats *OutputFormatsContext

	// AvailableTranslations maps page RelPath → set of language codes with
	// actual sidecar files. Set by BuildMultiSite; nil for single-language
	// builds. Used by buildTranslationLinks to filter hreflang output to
	// only languages that actually exist (prevents hreflang=en pointing to
	// 404 URL when no .en.md sidecar exists).
	AvailableTranslations map[string]map[string]bool
	// contains filtered or unexported fields
}

SiteContext mirrors Hugo's .Site object.

func NewSiteContext

func NewSiteContext(site *content.Site, cfg *config.Config) *SiteContext

NewSiteContext builds the shared SiteContext once, before any page context.

func (*SiteContext) GetPage

func (s *SiteContext) GetPage(args ...string) *Context

GetPage mirrors Hugo's .Site.GetPage - finds a page by ref/path. Usage: {{ .Site.GetPage "/posts/foo" }} or {{ .Site.GetPage "section" "name" }}

Hugo's GetPage, when given a path with no matching page, does NOT always return nil — for paths that look like valid page refs it can return a non-nil "zero page" stub with empty fields (RelPermalink=""). Templates that guard with {{ if ne $page nil }} therefore treat missing pages as found, emitting e.g. <a href="">title</a> (which minifies to <a href>title</a>). This is observable in zhurongshuo's products/index.html for Synton DB (data/products.yaml entry with no matching content/products/*.md file). To byte-match Hugo, we return a zero-valued Context stub for missing refs.

type TaxonomyContext

type TaxonomyContext map[string][]*Context

type TaxonomyDataContext

type TaxonomyDataContext struct {
	Terms TaxonomyTerms
}

TaxonomyDataContext for taxonomy listing pages.

type TaxonomyTerms

type TaxonomyTerms []TermCount

func (TaxonomyTerms) Alphabetical

func (t TaxonomyTerms) Alphabetical() TaxonomyTerms

ByCount_Alphabetical sorts terms alphabetically.

func (TaxonomyTerms) ByCount

func (t TaxonomyTerms) ByCount() TaxonomyTerms

ByCount sorts terms by count (descending), matching Hugo behavior.

type TermCount

type TermCount struct {
	Term  string
	Pages []*Context
	Count int
}

type TermSummaryExternal

type TermSummaryExternal struct {
	Name  string
	Pages PageSlice
	Count int
}

TermSummaryExternal is a taxonomy term with its pages, exposed to templates. Used by /tags/ term listing via .Data.Terms.ByCount.

type TermsList

type TermsList []TermSummaryExternal

TermsList is a sortable list of terms for template use.

func (TermsList) ByCount

func (t TermsList) ByCount() TermsList

ByCount sorts terms by count descending.

type TimeResult

type TimeResult struct {
	// contains filtered or unexported fields
}

TimeResult is what the time function returns.

func (*TimeResult) Format

func (t *TimeResult) Format(layout string) string

func (*TimeResult) Unix

func (t *TimeResult) Unix() int64
type TranslationLink struct {
	// Lang is the BCP-47 language code (e.g. "zh-cn", "en").
	Lang string
	// LanguageName is the display name (e.g. "中文", "English").
	LanguageName string
	// URL is the absolute URL (with baseURL) for this language variant.
	URL string
	// RelPermalink is the root-relative URL (with language prefix) for this variant.
	RelPermalink string
	// IsCurrent is true when this link matches the current page's language.
	IsCurrent bool
}

TranslationLink pairs a language code with its URL for the current page. Used by hreflang template function and language switcher UI.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL