Block macro splicing uses on_asg_created. The golem.plugins.apidoc plugin expands golem.apidoc:: block macros in the on_asg_created hook via an AST NodeTransformer — it operates directly on typed ASG nodes and preserves document structure.
Pluggy Plugin Hook Specifications
Golem utilizes pluggy—the plugin engine behind pytest—to provide clean lifecycle hooks.
Available Hook Specifications
Plugins implement hooks using the @hookimpl decorator from golem.plugins:
from pathlib import Path
from typing import Any
import click
from golem.plugins import hookimpl
class MyPlugin:
@hookimpl
def on_pre_parse(self, raw_content: str) -> str:
"""Called sequentially before Lark parsing. Can mutate raw AsciiDoc source text."""
return raw_content
@hookimpl
def on_ast_created(self, ast: Any) -> Any:
"""Called after Lark parses AsciiDoc source into an AST before semantic resolution."""
return ast
@hookimpl
def on_asg_created(self, asg: dict[str, Any], doc_path: Path | None = None) -> dict[str, Any]:
"""Called after semantic ASG resolution. Return a modified copy or the same dict.
`doc_path` is the source file path of the document being compiled, or None
for in-memory snippets. This hook is the preferred site for block-level
ASG transformations such as macro splicing.
"""
return asg
@hookimpl
def on_template_context(self, context: dict[str, Any], doc_path: Path) -> dict[str, Any]:
"""Called per document prior to Chameleon template rendering. Enriches context."""
context["custom_greeting"] = "Hello from MyPlugin!"
return context
@hookimpl
def on_post_render(self, html_content: str) -> str:
"""Called after Chameleon layout rendering before writing the HTML page to disk."""
return html_content
@hookimpl
def golem_add_subcommands(self, cli: click.Group) -> None:
"""Attach custom Click subcommands to the main golem CLI during bootstrap."""
@cli.command("mycmd")
def my_command():
click.echo("Custom plugin command executed!")
@hookimpl
def golem_mark_stale(
self,
changed_files: list[Path],
cache_metadata: dict[str, dict[str, Any]],
) -> list[Path] | None:
"""
Called during dependency analysis to allow plugins to register stale pages for recompilation.
Inspects `changed_files` and per-document `cache_metadata` (including `node_types`).
Returns a list of `Path` objects corresponding to pages that need recompilation.
"""
return []
Template Context Enrichment (on_template_context)
The on_template_context hook enables plugins to inject dynamic variables into the Chameleon template rendering scope immediately prior to HTML generation:
@hookimpl
def on_template_context(self, context: dict[str, Any], doc_path: Path) -> dict[str, Any]:
context.update({
"last_updated": datetime.now().isoformat(),
"custom_badge": "Beta",
})
return context
Best Practices for Context Enrichment
- Additive Enrichment: Use
context.update(...)or set unique, prefixed keys to avoid accidental collisions with core engine variables (title,body_html,nav_tree,toc_html,site_title,current_path). - Execution Order: Hooks execute sequentially in the exact order plugins are declared in
pluginswithingolem.toml. The context returned by each plugin is passed to subsequent plugins. - Document-Specific Context: Inspect
doc_pathor document attributes (context.get("doc_attributes")) to conditionally inject data (e.g. only adding index structures when:page-role: indexis present).
Registering Plugins via Entry Points
In your plugin package's pyproject.toml:
[project.entry-points."golem.plugins"]
my_plugin = "my_package.plugin:MyPlugin"
analytics = "my_package.analytics:AnalyticsPlugin"
When installed, users can enable and configure the plugin by referencing its registered entry-point name in golem.toml:
[plugins]
plugins = ["analytics"]
[plugins.analytics]
tracking_id = "UA-12345678-1"
- Pluggy
Python hook and plugin management library (the same engine that powers pytest). Golem's extension system is built on Pluggy.
- hookspec
A function decorated with
@hookspecthat declares the contract (name, signature, and behaviour) of a Golem extension point.- hookimpl
A function decorated with
@hookimplthat provides a concrete implementation of a hook declared by ahookspec.