jinja

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

README

jinja

A pure-Go Jinja template engine purpose-built for rendering LLM chat templates. It compiles and executes the Jinja templates embedded in GGUF model files, turning conversations and tool definitions into the exact token sequences each model expects. Zero dependencies, zero CGO.

Copyright 2026 Ardan Labs

[email protected]

Project Status

Go Reference Go Report Card go.mod Go version Linux

Install

go get github.com/ardanlabs/jinja

Quick Start

The API has two steps: compile a template once, then render it with data as many times as needed. Compiled templates are safe for concurrent use.

package main

import (
	"fmt"
	"log"

	"github.com/ardanlabs/jinja"
)

func main() {
	tmpl, err := jinja.Compile("Hello {{ name }}!")
	if err != nil {
		log.Fatal(err)
	}

	result, err := tmpl.Render(map[string]any{
		"name": "World",
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result)
	// Output: Hello World!
}

Chat Template Example

The primary use case is rendering LLM chat templates. Each model ships a Jinja template that formats conversations into the token layout the model was trained on.

const chatTemplate = `{%- if messages[0].role == 'system' -%}
<|im_start|>system
{{ messages[0].content }}<|im_end|>
{%- endif %}
{%- for message in messages -%}
{%- if message.role != 'system' %}
<|im_start|>{{ message.role }}
{{ message.content }}<|im_end|>
{%- endif -%}
{%- endfor %}
{%- if add_generation_prompt %}
<|im_start|>assistant
{%- endif -%}`

tmpl, err := jinja.Compile(chatTemplate)
if err != nil {
	log.Fatal(err)
}

result, err := tmpl.Render(map[string]any{
	"messages": []any{
		map[string]any{"role": "system", "content": "You are a helpful assistant."},
		map[string]any{"role": "user", "content": "What is the capital of France?"},
		map[string]any{"role": "assistant", "content": "The capital of France is Paris."},
		map[string]any{"role": "user", "content": "What about Germany?"},
	},
	"add_generation_prompt": true,
})

See the examples directory for more, including tool calling.

Supported Features

Template Syntax
  • Variable output: {{ expr }}
  • Statements: {% if %}, {% for %}, {% set %}, {% macro %}, {% block %}
  • Whitespace control: {%- ... -%}, {{- ... -}}
  • Comments: {# ... #}
  • String concatenation with ~
  • Inline if expressions: {{ x if condition else y }}
  • Slice notation: {{ items[::-1] }}
Filters

abs · batch · capitalize · count · default / d · dictsort · escape / e · first · float · fromjson · indent · int · items · join · last · length · list · lower · map · max · min · reject · rejectattr · replace · reverse · round · safe · select · selectattr · sort · string · sum · title · tojson · trim · unique · upper · wordcount

Tests

defined · undefined · none · boolean · integer · float · number · string · mapping · iterable · sequence · callable · true · false · odd · even · upper · lower · sameas · eq · ne · gt · ge · lt · le · in

Global Functions

namespace · range · dict · joiner · cycler · raise_exception · strftime_now

String Methods

.strip() · .split() · .startswith() · .endswith() · .upper() · .lower() · .replace() · .find() · .count() · .lstrip() · .rstrip()

Dict Methods

.get() · .items() · .keys() · .values() · .update()

Tested Models

The test suite compiles and renders the chat templates from these models:

Model Family
Qwen3-8B Qwen3
gpt-oss-20b GPT-OSS
Qwen3-VL-30B-A3B-Instruct Qwen3-VL
Qwen3.5-35B-A3B Qwen3.5
Qwen2-Audio-7B Qwen2-Audio
gemma-4-26B-A4B-it Gemma 4
Ministral-3-14B-Instruct-2512 Mistral 3
rnj-1-instruct RNJ-1
LFM2.5-VL-1.6B LFM2.5

License

Licensed under the Apache License, Version 2.0. See LICENSE for the full text.

Documentation

Overview

Package jinja implements a Jinja2-compatible template engine.

Package jinja implements a Jinja template engine purpose-built for LLM chat templates.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Callable

type Callable struct {
	Name string
	Fn   func(args []Value, kwargs map[string]Value) (Value, error)
}

Callable represents a named callable function within the template engine.

type Dict

type Dict struct {
	Keys []string
	Data map[string]Value
}

Dict is an ordered map of string keys to values. Insertion order is preserved via the Keys slice.

func (*Dict) Get

func (d *Dict) Get(key string) (Value, bool)

Get returns the value for key and reports whether it was found.

func (*Dict) Has

func (d *Dict) Has(key string) bool

Has reports whether key exists in the dict.

func (*Dict) Len

func (d *Dict) Len() int

Len returns the number of entries in the dict.

func (*Dict) OrderedKeys

func (d *Dict) OrderedKeys() []string

OrderedKeys returns the keys in insertion order.

func (*Dict) Set

func (d *Dict) Set(key string, val Value)

Set inserts or updates a key-value pair. New keys are appended to the insertion-order list.

type Kind

type Kind int

Kind represents the type of a template value.

const (
	KindUndefined Kind = iota
	KindNone
	KindBool
	KindInt
	KindFloat
	KindString
	KindList
	KindDict
	KindCallable
)

type List

type List struct {
	Items []Value
}

List holds an ordered sequence of values.

func (*List) Append

func (l *List) Append(v Value)

Append adds a value to the end of the list.

func (*List) Get

func (l *List) Get(i int) Value

Get returns the item at position i. It panics if i is out of range.

func (*List) Len

func (l *List) Len() int

Len returns the number of items in the list.

type Template

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

Template is a compiled Jinja template ready for rendering.

func Compile

func Compile(source string) (*Template, error)

Compile parses a Jinja template source string and returns a compiled template that can be rendered multiple times with different data.

func (*Template) Render

func (t *Template) Render(data map[string]any) (string, error)

Render executes the template with the provided data and returns the rendered string. Each call creates an isolated scope so templates are safe to render concurrently after compilation.

func (*Template) RenderValues

func (t *Template) RenderValues(data map[string]Value) (string, error)

RenderValues is like Render but accepts pre-converted Value data.

type Value

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

Value is a tagged union over JSON-like types used throughout the template engine. The v field holds one of: bool, int64, float64, string, *List, *Dict, or Callable.

func FromGoValue

func FromGoValue(v any) Value

FromGoValue converts a plain Go value to a Value. Supported source types are nil, bool, int, int64, float64, string, []any, map[string]any, and []Value. For map[string]any the keys are sorted for deterministic order. Unrecognized types produce Undefined.

func NewBool

func NewBool(b bool) Value

NewBool returns a boolean value.

func NewCallable

func NewCallable(name string, fn func(args []Value, kwargs map[string]Value) (Value, error)) Value

NewCallable returns a callable value.

func NewDict

func NewDict() Value

NewDict returns an empty dict value.

func NewFloat

func NewFloat(f float64) Value

NewFloat returns a floating-point value.

func NewInt

func NewInt(n int64) Value

NewInt returns an integer value.

func NewList

func NewList(items []Value) Value

NewList returns a list value containing the provided items.

func NewString

func NewString(s string) Value

NewString returns a string value.

func None

func None() Value

None returns a none value.

func Undefined

func Undefined() Value

Undefined returns an undefined value.

func (Value) AsBool

func (v Value) AsBool() bool

AsBool returns the bool held by v. It panics if v is not a bool.

func (Value) AsCallable

func (v Value) AsCallable() *Callable

AsCallable returns the *Callable held by v. It panics if v is not callable.

func (Value) AsDict

func (v Value) AsDict() *Dict

AsDict returns the *Dict held by v. It panics if v is not a dict.

func (Value) AsFloat

func (v Value) AsFloat() float64

AsFloat returns the float64 held by v. It panics if v is not a float.

func (Value) AsInt

func (v Value) AsInt() int64

AsInt returns the int64 held by v. It panics if v is not an int.

func (Value) AsList

func (v Value) AsList() *List

AsList returns the *List held by v. It panics if v is not a list.

func (Value) AsString

func (v Value) AsString() string

AsString returns the string held by v. It panics if v is not a string.

func (Value) Equals

func (v Value) Equals(other Value) bool

Equals reports whether v and other hold the same value.

func (Value) IsBool

func (v Value) IsBool() bool

IsBool reports whether v is a boolean.

func (Value) IsCallable

func (v Value) IsCallable() bool

IsCallable reports whether v is callable.

func (Value) IsDict

func (v Value) IsDict() bool

IsDict reports whether v is a dict.

func (Value) IsFloat

func (v Value) IsFloat() bool

IsFloat reports whether v is a float.

func (Value) IsInt

func (v Value) IsInt() bool

IsInt reports whether v is an integer.

func (Value) IsList

func (v Value) IsList() bool

IsList reports whether v is a list.

func (Value) IsNone

func (v Value) IsNone() bool

IsNone reports whether v is none.

func (Value) IsNumber

func (v Value) IsNumber() bool

IsNumber reports whether v is an integer or float.

func (Value) IsString

func (v Value) IsString() bool

IsString reports whether v is a string.

func (Value) IsTruthy

func (v Value) IsTruthy() bool

IsTruthy returns the Python-style truthiness of the value.

func (Value) IsUndefined

func (v Value) IsUndefined() bool

IsUndefined reports whether v is undefined.

func (Value) String

func (v Value) String() string

String returns a Python-style string representation of the value.

Directories

Path Synopsis
examples
basic command
This example demonstrates basic Jinja template rendering including variable substitution, for loops, conditionals, and filters.
This example demonstrates basic Jinja template rendering including variable substitution, for loops, conditionals, and filters.
chat command
This example demonstrates rendering an LLM chat template.
This example demonstrates rendering an LLM chat template.
toolcall command
This example demonstrates rendering a chat template that includes tool definitions, which is how function calling is formatted for LLMs.
This example demonstrates rendering a chat template that includes tool definitions, which is how function calling is formatted for LLMs.

Jump to

Keyboard shortcuts

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