hook

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package hook 提供宿主暴露给主题和插件脚本的统一扩展 API。

Index

Constants

View Source
const (
	PriorityEarly   = 5
	PriorityDefault = 10
	PriorityLate    = 20
)
View Source
const (
	// ActionHeadEnd 在主题 <head> 结束前触发,扩展可写入样式、脚本或 meta。
	// 主题模板中应当写 {{do_action "head.end" .}} 才能触发调用
	ActionHeadEnd = "head.end"
	// ActionBodyEnd 在主题 </body> 前触发,扩展可写入延迟脚本。
	// 主题模板中应当写 {{do_action "body.end" .}} 才能触发调用
	ActionBodyEnd = "body.end"
	// ActionCommentFormAfterTextarea 在评论表单 textarea 后触发,扩展可写入表情、附件等控件。
	// 默认情况下, 主题会使用 {{comment_form .}} 输出评论表单, 这个模板函数内部会触发本 action
	// 如果主题不使用这个模板函数, 而是自行输出评论表单, 则应当写 {{do_action "comment.form.after_textarea" .}} 才能触发调用
	ActionCommentFormAfterTextarea = "comment.form.after_textarea"
	// ActionAdminPostFormAfterTextarea 在后台文章编辑表单 textarea 后触发,扩展可写入表情、附件等控件。
	// 后台文章编辑页面 {{- do_action "admin.post.form.after_textarea" $ -}} 调用
	ActionAdminPostFormAfterTextarea = "admin.post.form.after_textarea"

	// FilterWidgetRenderHTML 过滤单个组件渲染后的可信 HTML。
	FilterWidgetRenderHTML = "widget.render_html"
	// FilterPostTitle 过滤文章/页面标题文本,运行于 post_title 模板函数内部。
	// 执行 post_title 模板函数时, 会应用这个 filter;返回值按纯文本处理并由宿主转义。
	FilterPostTitle = "post.title"
	// FilterPostExcerptHTML 过滤列表摘要可信 HTML,运行于 post_excerpt 模板函数内部。
	// 执行 post_excerpt 模板函数时, 会应用这个 filter
	FilterPostExcerptHTML = "post.excerpt_html"
	// FilterPostContentHTML 过滤详情正文可信 HTML,运行于 post_content 模板函数内部。
	// 执行 post_content 模板函数时, 会应用这个 filter
	FilterPostContentHTML = "post.content_html"
	// FilterPostFooterHTML 在文章正文末尾追加可信 HTML(如版权声明),运行于 post_content 模板函数内部。
	// 执行 post_content 模板函数时, 会应用这个 filter
	FilterPostFooterHTML = "post.footer_html"
	// FilterCommentContentHTML 过滤评论正文可信 HTML,运行于 comment_content 模板函数内部。
	// 主题通过 {{list_comments .}} 模板函数输出评论列表, 这个模板函数内部会触发本 filter
	// 如果主题自行输出评论, 需要自行调用 {{apply_filter .Content "comment.content_html"}}
	FilterCommentContentHTML = "comment.content_html"
	// FilterCommentBeforeCreate 在评论创建前触发,接收 *CommentPreCreateView,
	// 插件可修改其 Status 为 approved/pending/spam 来决定评论命运,也可修改 Content。
	// 返回 spam 且 RejectMessage 非空时,前端会收到 RejectMessage 作为错误提示。
	// 主题或 handler 在 CreateComment 前自行调用 r.ApplyFilters(ctx, FilterCommentBeforeCreate, view)。
	FilterCommentBeforeCreate = "comment.before_create"
	// FilterHeadMeta 过滤 OpenGraph / Twitter Card meta 标签可信 HTML,运行于 headMeta 模板函数内部。
	// 插件可改写、追加或清空 meta 标签(返回空字符串即清除)。
	// 主题调用 {{head_meta . }} 时, 触发 head_meta 模板函数执行, 内部会应用这个 filter
	FilterHeadMeta = "head.meta"
)
View Source
const (
	// SourceCore 表示由宿主核心注册的 hook。
	SourceCore = "core"
	// SourceTheme 表示由当前主题注册的 hook。
	SourceTheme = "theme"
	// SourcePlugin 表示由插件注册的 hook。
	SourcePlugin = "plugin"
)

Variables

View Source
var Consts = struct {
	ActionHeadEnd,
	ActionBodyEnd,
	ActionCommentFormAfterTextarea,
	ActionAdminPostFormAfterTextarea,
	FilterPostTitle,
	FilterPostExcerptHTML,
	FilterPostContentHTML,
	FilterPostFooterHTML,
	FilterCommentContentHTML,
	FilterCommentBeforeCreate,
	FilterWidgetRenderHTML,
	FilterHeadMeta string
	PriorityEarly,
	PriorityDefault,
	PriorityLate int
}{
	ActionHeadEnd:                    ActionHeadEnd,
	ActionBodyEnd:                    ActionBodyEnd,
	ActionCommentFormAfterTextarea:   ActionCommentFormAfterTextarea,
	ActionAdminPostFormAfterTextarea: ActionAdminPostFormAfterTextarea,
	FilterPostTitle:                  FilterPostTitle,
	FilterPostExcerptHTML:            FilterPostExcerptHTML,
	FilterPostContentHTML:            FilterPostContentHTML,
	FilterPostFooterHTML:             FilterPostFooterHTML,
	FilterCommentContentHTML:         FilterCommentContentHTML,
	FilterCommentBeforeCreate:        FilterCommentBeforeCreate,
	FilterWidgetRenderHTML:           FilterWidgetRenderHTML,
	FilterHeadMeta:                   FilterHeadMeta,
	PriorityEarly:                    PriorityEarly,
	PriorityDefault:                  PriorityDefault,
	PriorityLate:                     PriorityLate,
}

Consts 聚合所有 hook 名称常量和优先级值,供 yaegi 解释器一次性导出。 新增 hook 常量和优先级时只需修改此结构体,无需在 hook_exports.go 中逐个添加导出项。

Functions

func CurrentHook

func CurrentHook(ctx context.Context) string

CurrentHook 从 context 中读取当前正在执行的 hook 名称。

func DataLoaderFrom

func DataLoaderFrom(ctx context.Context) *store.DataLoader

DataLoaderFrom 从 context 中读取请求级 DataLoader。

func GetActionWriter

func GetActionWriter(ctx context.Context) io.Writer

GetActionWriter 从 context 中取出当前 action 的输出 writer。

func GetOption

func GetOption(getSetting func(key string) (string, error), themeName string, opt OptionDecl) string

GetOption 从 Setting 表读取 option 值,未配置时返回 default 值。

func GetOptionByID

func GetOptionByID(getSetting func(key string) (string, error), themeName string, options []OptionDecl, optionID string) string

GetOptionByID 从选项声明列表中查找指定 option 并读取其配置值。

func LoadTranslations

func LoadTranslations[T Translatable](items []T) error

LoadTranslations 遍历列表加载所有资源的翻译。

func OptionKey

func OptionKey(themeName, optionID string) string

OptionKey 返回 option 在 Setting 表中的 key。

func WithActionWriter

func WithActionWriter(ctx context.Context, w io.Writer) context.Context

WithActionWriter 把输出 writer 注入 context,供 api.Print/Printf/Println 使用。

func WithCurrentHook

func WithCurrentHook(ctx context.Context, name string) context.Context

WithCurrentHook 把当前 hook 名注入 context。

func WithDataLoader

func WithDataLoader(ctx context.Context, loader *store.DataLoader) context.Context

WithDataLoader 把当前请求的只读数据加载器绑定到 context,供插件 API 读取。

Types

type API

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

API 是暴露给插件脚本的宿主能力。

func NewAPI

func NewAPI() *API

NewAPI 创建一个 *API 实例

func (*API) AddAction

func (api *API) AddAction(name string, fn any, priority ...int)

AddAction 注册 action。

处理函数第一个参数必须是 *hook.API,且必须使用 ActionFunc 签名 func(*API, ...any) 或无额外参数的 func(*API)。

func (*API) AddFilter

func (api *API) AddFilter(name string, fn any, priority ...int)

AddFilter 注册 filter。

处理函数第一个参数必须是 *hook.API,第二个参数接收当前值,返回同类型值。 核心 filter 使用文档中的固定签名,通用 filter 使用 FilterFunc = func(*API, any, ...any) any。

func (*API) ArchiveMonths

func (api *API) ArchiveMonths() []ArchiveMonthView

ArchiveMonths 返回归档月份统计。

func (*API) AvatarURL

func (api *API) AvatarURL(email, defaultAvatar string, size int) string

AvatarURL 由邮箱生成 cravatar(国内镜像)头像 URL。

func (*API) Categories

func (api *API) Categories() []CategoryView

Categories 返回全部分类。

func (*API) CategoryURL

func (api *API) CategoryURL(slug string) string

CategoryURL 生成分类永久链接。

func (*API) CommentURL

func (api *API) CommentURL(post any, comment any) string

CommentURL 生成评论锚点链接,评论不在第一页时自动拼接 cpage 参数。

func (*API) CommentsByPost

func (api *API) CommentsByPost(postID any) []CommentView

CommentsByPost 返回指定文章的已批准评论。

func (*API) Debug

func (api *API) Debug(msg string, args ...any)

Debug 输出 Debug 级别日志,用法同 slog.DebugContext,参数为 key/value 交替对。

func (*API) Domain

func (api *API) Domain() string

func (*API) Error

func (api *API) Error(msg string, args ...any)

Error 输出 Error 级别日志。

func (*API) EscapeHTML

func (api *API) EscapeHTML(s string) string

EscapeHTML 转义 HTML 特殊字符。

func (*API) FuncNames

func (api *API) FuncNames() []string

FuncNames 返回所有已注册命名函数名称。

func (*API) GetFunc

func (api *API) GetFunc(name string) Func

GetFunc 获取已注册的命名函数。

func (*API) GetOption

func (api *API) GetOption(themeName, optionID string) string

GetOption 读取主题选项,未配置时回退到 theme.yaml 中的默认值。

func (*API) Info

func (api *API) Info(msg string, args ...any)

Info 输出 Info 级别日志。

func (*API) InvokeFunc

func (api *API) InvokeFunc(ctx context.Context, name string, args map[string]any) any

InvokeFunc 调用已注册的数据函数。

func (*API) N

func (api *API) N(singular, plural string, n int, args ...any) string

N 按数量翻译单复数消息。

func (*API) PageBySlug

func (api *API) PageBySlug(slug string) *PostView

PageBySlug 按 slug 获取页面。

func (*API) PageURL

func (api *API) PageURL(post any) string

PageURL 生成页面永久链接。

func (*API) Pages

func (api *API) Pages() []PostView

Pages 返回全部已发布页面。

func (*API) PluginOption

func (api *API) PluginOption(optionID, def string) string

PluginOption 读取插件全局选项,未配置时返回 def。

func (*API) Post

func (api *API) Post(postID any) *PostView

Post 按 ID 返回文章或页面。

func (*API) PostURL

func (api *API) PostURL(post any) string

PostURL 生成文章永久链接。

func (*API) Posts

func (api *API) Posts() []PostView

Posts 返回全部已发布文章(按发布时间倒序)。

func (*API) PostsByCategory

func (api *API) PostsByCategory(categorySlug string) []PostView

PostsByCategory 返回指定分类下的文章。

func (*API) PostsByTag

func (api *API) PostsByTag(tagSlug string) []PostView

PostsByTag 返回指定标签下的文章。

func (*API) PostsByYear

func (api *API) PostsByYear(year int) []PostView

PostsByYear 返回指定年份的文章。

func (*API) PostsByYearMonth

func (api *API) PostsByYearMonth(year, month int) []PostView

PostsByYearMonth 返回指定年月的文章。

func (*API) Print

func (api *API) Print(args ...any)

Print 向当前 action 的输出 writer 写入字符串。 仅在 action handler 内部调用有效;filter 中无 writer 注入。

func (*API) Printf

func (api *API) Printf(format string, args ...any)

Printf 向当前 action 的输出 writer 写入格式化字符串。 仅在 action handler 内部调用有效;filter 中无 writer 注入。

func (*API) Println

func (api *API) Println(args ...any)

Println 向当前 action 的输出 writer 写入参数并自动换行。

func (*API) RecentComments

func (api *API) RecentComments(n int) []CommentView

RecentComments 返回最近 n 条已批准评论。

func (*API) RecentPosts

func (api *API) RecentPosts(n int) []PostView

RecentPosts 返回最近 n 篇文章。

func (*API) RegisterFunc

func (api *API) RegisterFunc(name string, fn any)

RegisterFunc 注册一个可在模板中通过 hook_invoke 调用的数据函数。

签名必须是 func(api *hook.API, args hook.Args) any。

func (*API) RegistrationError

func (api *API) RegistrationError() error

RegistrationError 返回脚本 Register 阶段收集到的注册错误。

func (*API) RemoveAction

func (api *API) RemoveAction(name string)

RemoveAction 移除当前扩展注册的所有同名 action。

func (*API) RemoveFilter

func (api *API) RemoveFilter(name string)

RemoveFilter 移除当前扩展注册的所有同名 filter。

func (*API) Setting

func (api *API) Setting(key string) string

Setting 读取站点设置项。

func (*API) Settings

func (api *API) Settings(keys ...string) map[string]string

Settings 批量读取站点设置项。

func (*API) Snippet

func (api *API) Snippet(content any, n int) string

Snippet 截取一段文本摘要。

func (*API) T

func (api *API) T(msg string, args ...any) string

T 翻译普通消息。

func (*API) TagURL

func (api *API) TagURL(slug string) string

TagURL 生成标签永久链接。

func (*API) Tags

func (api *API) Tags() []TagView

Tags 返回全部标签。

func (*API) User

func (api *API) User(userID any) *UserView

User 按 ID 返回用户。

func (*API) Users

func (api *API) Users() []UserView

Users 返回全部用户。

func (*API) Warn

func (api *API) Warn(msg string, args ...any)

Warn 输出 Warn 级别日志。

func (*API) WithContext

func (api *API) WithContext(ctx context.Context) *API

WithContext 返回绑定到当前请求 context 的 API 副本。

func (*API) WithDomain

func (api *API) WithDomain(domain string) *API

func (*API) WithLoader

func (api *API) WithLoader(loader *store.DataLoader) *API

WithLoader 设置当前模板渲染请求的 DataLoader。

func (*API) WithRegistryBinding

func (api *API) WithRegistryBinding(binding RegistryBinding) *API

WithRegistryBinding 设置当前扩展注册和移除 hook 使用的 Registry 绑定。

func (*API) WithThemeOptions

func (api *API) WithThemeOptions(opts []OptionDecl) *API

WithThemeOptions 设置主题声明的选项列表(含默认值),供 GetOption 回退使用。

func (*API) X

func (api *API) X(ctx, msg string, args ...any) string

X 按上下文翻译消息。

func (*API) XN

func (api *API) XN(ctx, singular, plural string, n int, args ...any) string

XN 按上下文和数量翻译单复数消息。

type ActionFunc

type ActionFunc = func(api *API, args ...any)

ActionFunc 是插件注册 action 时推荐使用的函数签名。

type ArchiveMonthView

type ArchiveMonthView struct {
	Year  int
	Month int
	Count int64
}

ArchiveMonthView 是归档月份的只读视图。

type Args

type Args map[string]any

Args 是模板通过 hook_invoke 传给扩展函数的命名参数。

主题/插件作者可以直接用:

api.RegisterFunc("latest", func(api *hook.API, args hook.Args) any {
	return api.RecentPosts(args.Int("count", 5))
})

比起在每个扩展里重复写类型断言,这些小工具让 functions.goyaegi 的主流程更接近业务描述。

func (Args) Any

func (a Args) Any(key string) any

Any 返回原始参数值;不存在时返回 nil。

func (Args) Bool

func (a Args) Bool(key string, def bool) bool

Bool 读取布尔参数;支持 bool 和 strconv.ParseBool 可识别的字符串。

func (Args) Int

func (a Args) Int(key string, def int) int

Int 读取整数参数;支持常见整型、浮点数和数字字符串。

func (Args) PositiveInt

func (a Args) PositiveInt(key string, def int) int

PositiveInt 读取正整数参数;不存在、无法转换或小于等于 0 时返回 def。

func (Args) String

func (a Args) String(key, def string) string

String 读取字符串参数;空字符串或不存在时返回 def。

type CategoryView

type CategoryView struct {
	ID          uint
	Name        string
	Slug        string
	Description string
	ParentID    uint
	PostCount   int64
}

CategoryView 是扩展 API 暴露的分类只读视图。

type CommentPreCreateView

type CommentPreCreateView struct {
	PostID        uint
	ParentID      uint
	ReplyToID     uint
	UserID        *uint
	Author        string
	Email         string
	URL           string
	IP            string
	UserAgent     string
	Content       string
	Status        string // 初始为 pending/approved,插件可改为 pending/spam
	RejectMessage string // 当 Status 为 spam 时返回给前端的错误提示
}

CommentPreCreateView 是 comment.before_create filter 的上下文,评论入库前传入。 插件可修改 Status 为 approved/pending/spam 决定评论命运,也可修改 Content。 Status 为 spam 且 RejectMessage 非空时,前端将收到该错误提示。

type CommentView

type CommentView struct {
	ID        uint
	PostID    uint
	ParentID  uint
	ReplyToID uint
	UserID    *uint
	Author    string
	Email     string
	URL       string
	IP        string
	Content   string
	// Status: approved / pending / spam / deleted。
	Status        string
	NotifyOnReply bool
	CreatedAt     time.Time
	ReplyToAuthor string
	CommenterRole string
}

CommentView 是扩展 API 暴露的评论只读视图。

func CommentViewOf

func CommentViewOf(v any) *CommentView

CommentViewOf 将宿主评论模型或已有视图转换为扩展 API 的稳定只读视图。

type Executor

type Executor interface {
	DoAction(ctx context.Context, name string, w io.Writer, args ...any)
	ApplyFilters(ctx context.Context, name string, value any, args ...any) any
}

Executor 是 Hook Registry 的最小接口,render 包只需要 DoAction 和 ApplyFilters。

type FilterFunc

type FilterFunc = func(api *API, value any, args ...any) any

FilterFunc 是插件注册 filter 时推荐使用的函数签名。

type Func

type Func = func(api *API, args Args) any

Func 是插件注册给模板调用的数据函数。

type FuncInvoker

type FuncInvoker interface {
	InvokeFunc(ctx context.Context, name string, args map[string]any) any
}

FuncInvoker 是调用模板扩展函数所需的最小能力集合。

type FuncRegistry

type FuncRegistry interface {
	FuncInvoker
	RegisterFunc(name string, fn any)
	GetFunc(name string) Func
	FuncNames() []string
}

FuncRegistry 是注册和查询模板扩展函数所需的最小能力集合。

type Handler

type Handler struct {
	Name     string // 名称
	Priority int    // 优先级
	Source   Source // 来源
	Fn       any    // 函数实现
	// contains filtered or unexported fields
}

Handler 是注册到某个 action/filter 上的处理器。

type Handlers

type Handlers []Handler

func (Handlers) Len

func (h Handlers) Len() int

func (Handlers) Less

func (h Handlers) Less(i, j int) bool

func (Handlers) Swap

func (h Handlers) Swap(i, j int)

type HeadMetaView

type HeadMetaView struct {
	Title        string
	Description  string
	CanonicalURL string
	SiteName     string
	OGType       string
	TwitterCard  string
}

HeadMetaView 是 head.meta filter 的稳定上下文。

type Hooks

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

Hooks 保存所有 action/filter 处理器。

func NewRegistry

func NewRegistry() *Hooks

NewRegistry 创建一个空 Hook Registry。

func (*Hooks) Actions

func (r *Hooks) Actions(name string) []Handler

Actions 返回指定 action 当前注册的处理器快照。

func (*Hooks) AddAction

func (r *Hooks) AddAction(name string, fn any, source Source, priority ...int)

AddAction 注册 action 处理器。

func (*Hooks) AddFilter

func (r *Hooks) AddFilter(name string, fn any, source Source, priority ...int)

AddFilter 注册 filter 处理器。

func (*Hooks) ApplyFilters

func (r *Hooks) ApplyFilters(ctx context.Context, name string, value any, args ...any) any

ApplyFilters 依次执行 filter,并把上一个 filter 的返回值传给下一个 filter。

func (*Hooks) DidAction

func (r *Hooks) DidAction(name string) int

DidAction 返回指定 action 已被触发的次数。

func (*Hooks) DoAction

func (r *Hooks) DoAction(ctx context.Context, name string, w io.Writer, args ...any)

DoAction 执行一个 action。单个处理器 panic 不会中断后续处理器。 w 是输出 writer,会自动注入 context 供 api.Print/Printf/Println 使用。

func (*Hooks) DoingAction

func (r *Hooks) DoingAction(ctx context.Context, name string) bool

DoingAction 返回指定 action 当前是否正在执行中。

func (*Hooks) Filters

func (r *Hooks) Filters(name string) []Handler

Filters 返回指定 filter 当前注册的处理器快照。

func (*Hooks) RemoveAction

func (r *Hooks) RemoveAction(name string, source Source) int

RemoveAction 移除指定 source 注册的所有同名 action 处理器。 返回实际移除的数量。

func (*Hooks) RemoveFilter

func (r *Hooks) RemoveFilter(name string, source Source) int

RemoveFilter 移除指定 source 注册的所有同名 filter 处理器。 返回实际移除的数量。

func (*Hooks) ReplaceAllFrom

func (r *Hooks) ReplaceAllFrom(other *Hooks)

ReplaceAllFrom 原子替换所有 hook 处理器,用于插件重载场景。 编译到临时 Registry 成功后调用此方法,避免替换 Registry 实例本身。

type I18nAPI

type I18nAPI interface {
	T(msg string, args ...any) string
	N(singular, plural string, n int, args ...any) string
	X(ctx, msg string, args ...any) string
	XN(ctx, singular, plural string, n int, args ...any) string
}

I18nAPI 是脚本翻译所需的最小能力集合。

type OptionAPI

type OptionAPI interface {
	PluginOption(optionID, def string) string
	Setting(key string) string
	Settings(keys ...string) map[string]string
	GetOption(themeName, optionID string) string
}

OptionAPI 是读取插件选项、主题选项和站点设置所需的最小能力集合。

type OptionDecl

type OptionDecl struct {
	ID          string      `yaml:"id" json:"id"`
	Type        string      `yaml:"type" json:"type"`
	Label       string      `yaml:"label" json:"label"`
	Description string      `yaml:"description" json:"description"`
	Default     string      `yaml:"default" json:"default"`
	Min         *float64    `yaml:"min" json:"min,omitempty"`
	Max         *float64    `yaml:"max" json:"max,omitempty"`
	Options     []SelectOpt `yaml:"options" json:"options,omitempty"`
}

OptionDecl 描述主题或扩展声明的一个可配置选项。

type PostView

type PostView struct {
	ID           uint
	Title        string
	Slug         string
	Excerpt      string
	Content      string
	AuthorID     uint
	Status       string
	PostType     string
	Views        int64
	MenuOrder    int
	PublishedAt  time.Time
	ModifiedAt   time.Time
	CommentCount int64
	Author       UserView
	Categories   []CategoryView
	Tags         []TagView
}

PostView 是扩展 API 暴露的文章/页面只读视图。

func PostViewOf

func PostViewOf(v any, loader *store.DataLoader) *PostView

PostViewOf 将宿主文章模型或已有视图转换为扩展 API 的稳定只读视图。

func (PostView) PostURLFields

func (p PostView) PostURLFields() struct {
	ID          uint
	Title       string
	Slug        string
	PostType    string
	PublishedAt time.Time
	ModifiedAt  time.Time
}

PostURLFields 返回生成文章/页面永久链接所需的最小字段集。 返回类型保持匿名结构,避免 hook 包反向依赖 render 包。

type QueryAPI

type QueryAPI interface {
	Posts() []PostView
	Post(postID any) *PostView
	Pages() []PostView
	PageBySlug(slug string) *PostView
	RecentPosts(n int) []PostView
	PostsByCategory(categorySlug string) []PostView
	PostsByTag(tagSlug string) []PostView
	PostsByYear(year int) []PostView
	PostsByYearMonth(year, month int) []PostView
	Categories() []CategoryView
	Tags() []TagView
	CommentsByPost(postID any) []CommentView
	RecentComments(n int) []CommentView
	Users() []UserView
	User(userID any) *UserView
	ArchiveMonths() []ArchiveMonthView
	PostURL(post any) string
	PageURL(post any) string
	CommentURL(post any, comment any) string
	CategoryURL(slug string) string
	TagURL(slug string) string
	Snippet(content any, n int) string
	AvatarURL(email, defaultAvatar string, size int) string
}

QueryAPI 是读取站点公开内容和生成前台 URL 所需的最小能力集合。

type Registrar

type Registrar interface {
	AddAction(name string, fn any, priority ...int)
	AddFilter(name string, fn any, priority ...int)
	RemoveAction(name string)
	RemoveFilter(name string)
	RegisterFunc(name string, fn any)
	RegistrationError() error
}

Registrar 是脚本 Register 函数所需的最小能力集合。 编译期传入脚本,只包含注册能力,阻止脚本在 Register 中误用请求期方法。

type Registry

type Registry interface {
	Executor
	AddAction(name string, fn any, source Source, priority ...int)
	AddFilter(name string, fn any, source Source, priority ...int)
	RemoveAction(name string, source Source) int
	RemoveFilter(name string, source Source) int
	DidAction(name string) int
	DoingAction(ctx context.Context, name string) bool
}

Registry 是 hook 注册与执行接口。 theme 包通过此接口使用 hook 能力,plugin 包的 Registry 实现此接口。

type RegistryBinding

type RegistryBinding struct {
	AddAction    func(name string, fn any, priority ...int)
	AddFilter    func(name string, fn any, priority ...int)
	RemoveAction func(name string)
	RemoveFilter func(name string)
}

RegistryBinding 是 API 注册 action/filter 时使用的 Hook Registry 绑定。

func NewRegistryBinding

func NewRegistryBinding(registry Registry, source Source) RegistryBinding

NewRegistryBinding 创建绑定到指定来源的 Hook Registry 配置。

type RenderAPI

type RenderAPI interface {
	Print(args ...any)
	Printf(format string, args ...any)
	Println(args ...any)
	EscapeHTML(s string) string
}

RenderAPI 是 action 输出和 HTML 转义所需的最小能力集合。

type SelectOpt

type SelectOpt struct {
	Value string `yaml:"value" json:"value"`
	Label string `yaml:"label" json:"label"`
}

SelectOpt 是 select 类型选项的一个可选项。

type SettingStore

type SettingStore interface {
	GetSetting(ctx context.Context, key string) (string, error)
	SetSetting(ctx context.Context, key, value string) error
}

SettingStore 是主题/插件管理器需要的设置存储接口。

type Source

type Source struct {
	Type string // core / theme / plugin
	ID   string // default / twentytwenty / saying
}

Source 记录一个 hook 处理器来自核心、主题还是插件。

type TagView

type TagView struct {
	ID        uint
	Name      string
	Slug      string
	PostCount int64
}

TagView 是扩展 API 暴露的标签只读视图。

type Translatable

type Translatable interface {
	LoadTranslations() error
}

Translatable 表示可加载翻译的资源(主题或插件)。

type UserView

type UserView struct {
	ID          uint
	Username    string
	DisplayName string
	Email       string
	Website     string
	Role        string
}

UserView 是扩展 API 暴露的用户只读视图。

type WidgetDecl

type WidgetDecl struct {
	ID       string       `yaml:"id" json:"id"`
	Label    string       `yaml:"label" json:"label"`
	Options  []OptionDecl `yaml:"options,omitempty" json:"options,omitempty"`
	Source   string       `yaml:"-" json:"source,omitempty"`
	PluginID string       `yaml:"-" json:"plugin_id,omitempty"`
}

WidgetDecl 描述主题或插件声明的一个可用组件。

type WidgetDeclProvider

type WidgetDeclProvider = func(ctx context.Context) []WidgetDecl

type WidgetInstance

type WidgetInstance struct {
	InstanceID string            // 实例唯一 ID
	WidgetID   string            // 组件类型 ID
	Settings   map[string]string // 实例级配置值
}

WidgetInstance 表示一个组件实例的运行时状态,包含实例 ID 和配置值。 同一组件类型可以在同一区域添加多次,每次有独立的 InstanceID 和 Settings。

type WidgetRegistry

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

WidgetRegistry 管理所有已注册的组件 renderer,按 source:id 或 plugin:pluginID:id 索引。 theme 和 plugin 包各自通过 Register 方法将组件注册进来, 模板渲染阶段通过 Get 方法查找 renderer。

func NewWidgetRegistry

func NewWidgetRegistry() *WidgetRegistry

NewWidgetRegistry 创建组件注册表。

func (*WidgetRegistry) Get

func (r *WidgetRegistry) Get(source, id, pluginID string) WidgetRenderer

Get 按来源和 ID 查找组件 renderer。 source 为 "builtin" / "theme" / "plugin",pluginID 仅在 source="plugin" 时有值。

func (*WidgetRegistry) Register

func (r *WidgetRegistry) Register(w WidgetRenderer)

Register 注册一个组件 renderer。

type WidgetRenderView

type WidgetRenderView struct {
	Area         string
	InstanceID   string
	ID           string
	Source       string
	PluginID     string
	TemplateName string
	Options      map[string]string
}

WidgetRenderView 是 widget.render_html filter 的稳定上下文。

type WidgetRenderer

type WidgetRenderer interface {
	// Meta 返回组件声明元数据(ID、标签、可配置选项等)。
	Meta() WidgetDecl
	// Render 渲染组件为 HTML。tpl 是当前请求的主题模板实例;内置/主题组件通常用它执行
	// 主题模板,插件组件可以使用自己的模板渲染机制。
	Render(ctx context.Context, tpl *template.Template, instance WidgetInstance, data any) (template.HTML, error)
}

WidgetRenderer 是所有组件(内置/主题/插件)的统一渲染接口。 核心负责注册、解析、实例配置和外层生命周期,组件实现者只提供元数据和渲染逻辑。

type WidgetResolver

type WidgetResolver = func(source, id, pluginID string) WidgetRenderer

WidgetResolver 根据来源和 ID 查找组件 renderer。 source 为 "builtin" / "theme" / "plugin",pluginID 仅在 source="plugin" 时有值。

Jump to

Keyboard shortcuts

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