For AI agents: the complete documentation index is available at https://docs.halo.run/llms.txt, the full documentation bundle is available at https://docs.halo.run/llms-full.txt, and this page is available as Markdown at https://docs.halo.run/developer-guide/plugin/extension-points/server/template-head-processor.md.

主题端 HTML Head 标签处理

主题端 HTML Head 标签处理扩展点的作用是干预 HTML 页面中的 Head 标签内容,可以添加自定义的 CSS、JS 及 meta 标签等,以满足特定的定制化需求。

如果标签可能同时由主题或其他插件提供,应提供可关闭的插件设置并检查最终页面,避免重复或冲突。完整边界参考与主题集成

使用场景

  • 添加自定义样式或脚本:在 HTML Head 中插入额外的 CSS 文件或 JavaScript 脚本文件,以增强页面的交互性或样式。
  • 定制 Meta 标签:为特定页面添加或修改 meta 标签,如描述、作者、关键词等,以提高 SEO 和页面信息的完整性。
  • 引入第三方库:引入第三方库(如 Google Fonts、Font Awesome 等),以满足页面的特殊功能或风格需求。
  • 定制 Open Graph 等社交媒体标签:为社交媒体分享优化页面标签内容。

扩展点定义

主题端 HTML Head 标签处理的扩展点定义为 TemplateHeadProcessor,对应的 ExtensionPoint 类型为 MULTI_INSTANCE,即可以有多个实现类。

@FunctionalInterface
public interface TemplateHeadProcessor extends ExtensionPoint {

    Mono<Void> process(ITemplateContext context, IModel model,
        IElementModelStructureHandler structureHandler);
}

TemplateHeadProcessor 对应的 ExtensionPointDefinition 资源描述如下:

apiVersion: plugin.halo.run/v1alpha1
kind: ExtensionPointDefinition
metadata:
  name: template-head-processor
spec:
  className: run.halo.app.theme.dialect.TemplateHeadProcessor
  displayName: TemplateHeadProcessor
  type: MULTI_INSTANCE
  description: "Provides a way to extend the head tag content in the theme-side HTML page."

即声明 ExtensionDefinition 自定义模型对象时对应的 extensionPointNametemplate-head-processor

示例实现

以下是一个简单的 TemplateHeadProcessor 插件实现示例:

@Component
public class CustomHeadProcessor implements TemplateHeadProcessor {

    @Override
    public Mono<Void> process(ITemplateContext context, IModel model,
        IElementModelStructureHandler structureHandler) {
        var factory = context.getModelFactory();
        // 添加自定义 CSS 文件
        model.add(factory.createStandaloneElementTag(
            "link",
            Map.of("rel", "stylesheet", "href", "/custom/styles.css"),
            AttributeValueQuotes.DOUBLE,
            false,
            true
        ));

        // 添加自定义 Meta 标签
        model.add(factory.createStandaloneElementTag(
            "meta",
            Map.of("name", "author", "content", "Your Name"),
            AttributeValueQuotes.DOUBLE,
            false,
            true
        ));
        return Mono.empty();
    }
}

多个处理器会按 Spring @Order 顺序执行。源码参考:TemplateHeadProcessor

声明 ExtensionDefinition 自定义模型对象时对应的 extensionPointName 为 template-head-processor。

apiVersion: plugin.halo.run/v1alpha1
kind: ExtensionDefinition
metadata:
  name: custom-head-extension
spec:
  extensionPointName: template-head-processor
  className: com.example.CustomHeadProcessor
  displayName: "Custom Head Extension"
  description: "Adds custom CSS and meta tags to the head section."

使用此扩展点的插件