gohtml

package module
v0.0.0-...-b2d0c60 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2026 License: MIT Imports: 6 Imported by: 0

README

GoHTML

Go Reference Go Report Card

中文 | English

A collection of powerful and easy-to-use Go HTML template engines with unified interfaces, featuring template inheritance, hot reload, and rich built-in functions.

Template Engines

GoHTML provides three template engine implementations:

📦 template - Go Standard Library Based

Built on Go's standard html/template library with template inheritance support.

Features:

  • 🎯 Template inheritance with {{ extends "parent.gohtml" }}
  • 🔒 Auto-escaping for XSS protection
  • 🧩 20+ built-in functions
  • 0️⃣ Zero external dependencies

→ View template package documentation

jet - High Performance

Wrapper for the Jet template engine with Django/Jinja2-like syntax.

Features:

  • ⚡ One of the fastest Go template engines
  • 🎨 Django/Jinja2-style syntax
  • 🔧 Highly extensible
  • 🌐 Built-in template inheritance

→ View jet package documentation

🎨 pongo2 - Django Compatible

Wrapper for the Pongo2 template engine with Django template compatibility.

Features:

  • 🎨 Django-compatible syntax
  • 🔒 Auto-escaping with XSS protection
  • 🔧 Custom filters and tags
  • 🌐 Built-in template inheritance

→ View pongo2 package documentation

Installation

go get github.com/h3go/gohtml

Quick Start

Using the template package (Standard Library)
package main

import (
    "bytes"
    "fmt"
    "github.com/h3go/gohtml/template"
)

func main() {
    engine := template.New()
    engine.JoinDir("./templates")
    
    var buf bytes.Buffer
    engine.Render(&buf, "index", map[string]any{
        "Title":   "Welcome",
        "Message": "Hello, GoHTML!",
    })
    
    fmt.Println(buf.String())
}
Using the jet package
package main

import (
    "bytes"
    "github.com/h3go/gohtml/jet"
)

func main() {
    engine := jet.New()
    engine.JoinDir("./templates")
    
    var buf bytes.Buffer
    engine.Render(&buf, "index.jet", map[string]any{
        "Title":   "Welcome",
        "Message": "Hello, Jet!",
    })
}
Using the pongo2 package
package main

import (
    "bytes"
    "github.com/h3go/gohtml/pongo2"
)

func main() {
    engine := pongo2.New()
    engine.JoinDir("./templates")
    
    var buf bytes.Buffer
    engine.Render(&buf, "index.html", map[string]any{
        "Title":   "Welcome",
        "Message": "Hello, Pongo2!",
    })
}

HTTP Middleware Integration

GoHTML provides HTTP middleware for easy integration with web applications:

package main

import (
    "net/http"
    "github.com/h3go/gohtml"
    "github.com/h3go/gohtml/template"
)

func main() {
    engine := template.New()
    engine.JoinDir("./templates")
    
    mux := http.NewServeMux()
    
    // Use middleware to inject engine and global data
    handler := gohtml.Middleware(engine, map[string]any{
        "SiteName": "My Website",
        "Version":  "1.0.0",
    })(mux)
    
    // Route handler
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        err := gohtml.Render(r.Context(), w, "index", map[string]any{
            "Title":   "Home",
            "Content": "Welcome",
        })
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
    })
    
    http.ListenAndServe(":8080", handler)
}

Context Functions API

import "github.com/h3go/gohtml"

// Store engine in context
func WithEngine(ctx context.Context, engine Engine) context.Context

// Get engine from context
func FromContext(ctx context.Context) (Engine, bool)

// Store single data item in context
func WithDatum(ctx context.Context, key string, value any) context.Context

// Store multiple data items in context
func WithData(ctx context.Context, dataMap map[string]any) context.Context

// Get all data from context
func GetData(ctx context.Context) map[string]any

// Get engine from context and render template (auto-merge global data)
func Render(ctx context.Context, w io.Writer, name string, data map[string]any) error

HTTP Middleware API

import "github.com/h3go/gohtml"

// Create HTTP middleware
// engine: the template engine to inject into requests
// globals: optional global data to inject into all templates
func Middleware(engine Engine, globals ...map[string]any) func(next http.Handler) http.Handler

Choosing a Template Engine

Feature template jet pongo2
Performance Good Excellent Good
Syntax Go template Django/Jinja2 Django
Dependencies None 1 external 1 external
Auto-escaping
Template Inheritance
Custom Functions
embed.FS Support
Best For Standard Go projects High-performance apps Django developers

Documentation

License

MIT License - See LICENSE

Contributing

Issues and Pull Requests are welcome!

Author

h3go

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound = errors.New("gohtml: no template")
	ErrSyntax   = errors.New("gohtml: syntax error")
	ErrNoEngine = errors.New("gohtml: no engine found")
)

Functions

func GetData

func GetData(ctx context.Context) map[string]any

GetData 从 context 中获取所有模板数据 返回注入的全局模板数据的拷贝,如果没有则返回空 map

示例:

data := gohtml.GetData(r.Context())
data["Title"] = "Home Page"  // 添加页面特定数据
result, _ := engine.Render("index", data)

func Middleware

func Middleware(engine Engine, globals ...map[string]any) func(next http.Handler) http.Handler

Middleware 返回一个 HTTP 中间件,将 Engine 注入到请求的 context 中 这样在请求处理器中就可以通过 FromContext 获取模板引擎来渲染模板

参数:

  • engine: 模板引擎实例,会被注入到所有请求的 context 中
  • globals: 可选的全局模板数据,会自动合并到所有模板渲染中 可用于注入通用数据如站点名称、用户信息等

用法:

// 基础用法
mux.Use(gohtml.Middleware(engine))

// 带全局数据
mux.Use(gohtml.Middleware(engine, map[string]any{
    "siteName": "My Site",
    "version": "1.0.0",
}))

// 在处理器中使用
func handler(w http.ResponseWriter, r *http.Request) {
    engine, _ := gohtml.FromContext(r.Context())
    engine.Render(w, r.Context(), "page.gohtml", map[string]any{
        "title": "Home",
    })
}

func Render

func Render(ctx context.Context, writer io.Writer, name string, data map[string]any) error

Render 从 context 中获取引擎并渲染模板 此函数会自动合并 context 中的全局数据和传入的 data

参数:

  • ctx: context.Context,必须包含通过 WithEngine 注入的引擎
  • writer: io.Writer,渲染结果将写入此 writer
  • name: 模板名称
  • data: 页面特定的数据,会覆盖 context 中的同名键

示例:

err := gohtml.Render(r.Context(), w, "index", map[string]any{
	"Title": "首页",
})

func WithData

func WithData(ctx context.Context, dataMap map[string]any) context.Context

WithData 将多个模板数据存储到 context 中 用于在中间件中批量注入全局模板数据,这些数据会自动合并到所有模板渲染中

示例:

globals := map[string]any{
	"SiteName": "My Website",
	"Version":  "1.0.0",
	"Year":     2024,
}
ctx := gohtml.WithData(r.Context(), globals)

func WithDatum

func WithDatum(ctx context.Context, key string, value any) context.Context

WithDatum 将模板数据存储到 context 中 用于在中间件中注入全局模板数据,这些数据会自动合并到所有模板渲染中

示例:

ctx := gohtml.WithDatum(r.Context(), "SiteName", "My Website")
ctx = gohtml.WithDatum(ctx, "Year", 2024)
// 在模板中可以直接使用 {{ .SiteName }} 和 {{ .Year }}

func WithEngine

func WithEngine(ctx context.Context, engine Engine) context.Context

WithEngine 将 Engine 存储到 context 中 返回包含 Engine 的新 context

示例:

engine := gohtml.New()
engine.JoinDir("./templates")
ctx := gohtml.WithEngine(context.Background(), engine)

Types

type Engine

type Engine interface {
	Render(w io.Writer, name string, data map[string]any) error
}

Engine 是模板引擎接口

func FromContext

func FromContext(ctx context.Context) (Engine, bool)

FromContext 从 context 中获取 Engine 如果 context 中没有 Engine,返回 nil 和 false

示例:

engine, ok := gohtml.FromContext(r.Context())
if !ok {
	http.Error(w, "engine not found", http.StatusInternalServerError)
	return
}
result, _ := engine.Render("index", data)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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