tmpltype

module
v0.0.0-...-58acc5f Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2025 License: MIT

README

tmpltype

Go Reference

English | 日本語


English

A Go code generator that creates type-safe template rendering functions from Go template files.

What is tmpltype?

tmpltype eliminates runtime errors in Go templates by generating type-safe structs and render functions. It analyzes your template files and automatically infers parameter types, or you can specify them explicitly.

Before (runtime errors):

// ❌ Typo in field name - fails at runtime
tmpl.Execute(w, map[string]any{"Nmae": "Alice"})

After (compile-time safety):

// ✅ Compile error if field name is wrong
RenderEmail(w, Email{Name: "Alice", Message: "Welcome!"})
Quick Start

Install:

go install github.com/bellwood4486/tmpltype/cmd/tmpltype@latest

1. Create a template (templates/email.tmpl):

<h1>Hello {{ .User.Name }}</h1>
<p>{{ .Message }}</p>

2. Add go:generate directive (gen.go):

package main

//go:generate tmpltype -dir templates -pkg main -out template_gen.go

3. Generate and use:

go generate
package main

import (
    "bytes"
    "fmt"
)

func main() {
    var buf bytes.Buffer
    _ = RenderEmail(&buf, Email{
        User:    EmailUser{Name: "Alice"},
        Message: "Welcome!",
    })
    fmt.Println(buf.String())
}
Key Features
  • 🔒 Type Safety: Catch template errors at compile time, not runtime
  • 🤖 Type Inference: Automatically infers types from template syntax
  • 📝 Explicit Types: Use @param directives for complex types (int, pointers, custom structs)
  • 📁 Template Grouping: Organize templates in subdirectories with nested namespaces
  • 🎨 Custom Functions: Use any custom template functions with functional option pattern
  • 🔧 go generate: Seamless integration with Go's standard workflow
  • 💡 IDE Support: Full autocompletion for template parameters
  • 🔍 Debug Logging: Optional detailed logging via TMPLTYPE_LOG_LEVEL=debug for understanding type inference
Documentation
Getting Started
Reference
日本語ドキュメント
Examples

Explore working examples in the examples/ directory:

Run an example:

cd examples/01_basic
go generate
go run .
Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.


日本語

Goテンプレートファイルから型安全なテンプレート描画関数を生成するGoコードジェネレータです。

tmpltypeとは?

tmpltypeはGoテンプレートでのランタイムエラーを排除し、型安全な構造体とレンダー関数を生成します。テンプレートファイルを解析してパラメータの型を自動推論するか、明示的に指定することができます。

従来の方法(ランタイムエラー):

// ❌ フィールド名のタイポ - 実行時に失敗
tmpl.Execute(w, map[string]any{"Nmae": "Alice"})

tmpltype使用後(コンパイル時の安全性):

// ✅ フィールド名が間違っているとコンパイルエラー
RenderEmail(w, Email{Name: "Alice", Message: "ようこそ!"})
クイックスタート

インストール:

go install github.com/bellwood4486/tmpltype/cmd/tmpltype@latest

1. テンプレートを作成 (templates/email.tmpl):

<h1>こんにちは {{ .User.Name }}</h1>
<p>{{ .Message }}</p>

2. go:generateディレクティブを追加 (gen.go):

package main

//go:generate tmpltype -dir templates -pkg main -out template_gen.go

3. 生成して使用:

go generate
package main

import (
    "bytes"
    "fmt"
)

func main() {
    var buf bytes.Buffer
    _ = RenderEmail(&buf, Email{
        User:    EmailUser{Name: "太郎"},
        Message: "ようこそ!",
    })
    fmt.Println(buf.String())
}
主な機能
  • 🔒 型安全性: テンプレートエラーを実行時ではなくコンパイル時に検出
  • 🤖 型推論: テンプレート構文から自動的に型を推論
  • 📝 明示的な型指定: 複雑な型(int、ポインタ、カスタム構造体)には@paramディレクティブを使用
  • 📁 テンプレートグルーピング: サブディレクトリでテンプレートを整理し、ネストされた名前空間を生成
  • 🎨 カスタム関数: functional optionパターンで任意のカスタムテンプレート関数を使用可能
  • 🔧 go generate: Goの標準ワークフローにシームレスに統合
  • 💡 IDE サポート: テンプレートパラメータの完全な自動補完
  • 🔍 デバッグログ: TMPLTYPE_LOG_LEVEL=debugで型推論を理解するための詳細ログ出力
ドキュメント
はじめに
  • はじめに - ステップバイステップのチュートリアル
  • サンプル - よくあるパターンの動作するコード例
リファレンス
English Documentation
サンプル

examples/ディレクトリの動作するサンプルをご覧ください:

サンプルの実行:

cd examples/01_basic
go generate
go run .
コントリビューション

コントリビューションを歓迎します!プルリクエストを自由に提出してください。

ライセンス

このプロジェクトはMITライセンスのもとでライセンスされています - 詳細はLICENSEファイルを参照してください。

Directories

Path Synopsis
cmd
tmpltype command
examples
01_basic command
Code generated by tmpltype; DO NOT EDIT.
Code generated by tmpltype; DO NOT EDIT.
02_param_directive command
Code generated by tmpltype; DO NOT EDIT.
Code generated by tmpltype; DO NOT EDIT.
03_multi_template command
Code generated by tmpltype; DO NOT EDIT.
Code generated by tmpltype; DO NOT EDIT.
04_comprehensive_template command
Code generated by tmpltype; DO NOT EDIT.
Code generated by tmpltype; DO NOT EDIT.
05_all_param_types command
Code generated by tmpltype; DO NOT EDIT.
Code generated by tmpltype; DO NOT EDIT.
06_non_ascii_filename command
Code generated by tmpltype; DO NOT EDIT.
Code generated by tmpltype; DO NOT EDIT.
07_grouping command
Code generated by tmpltype; DO NOT EDIT.
Code generated by tmpltype; DO NOT EDIT.
08_custom_functions command
Code generated by tmpltype; DO NOT EDIT.
Code generated by tmpltype; DO NOT EDIT.
internal
gen
Package gen はテンプレートからGoコードを生成します。
Package gen はテンプレートからGoコードを生成します。
logger
Package logger provides a global logger for tmpltype using slog.
Package logger provides a global logger for tmpltype using slog.
scan
Package scan はGoテンプレートをスキャンしてスキーマを推論します。
Package scan はGoテンプレートをスキャンしてスキーマを推論します。
typing
Package typing はスキャン結果から最終的な型を解決します。
Package typing はスキャン結果から最終的な型を解決します。
typing/magic
Package magic は @param マジックコメントのパースと型オーバーライドを提供します。
Package magic は @param マジックコメントのパースと型オーバーライドを提供します。
util
Package util はtmpltype全体で使用されるユーティリティ関数を提供します。
Package util はtmpltype全体で使用されるユーティリティ関数を提供します。

Jump to

Keyboard shortcuts

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