Skip to content
ardanlabsPublic

About

Jinja template engine for Go programs

Resources

Stars

21 stars

Watchers

2 watching

Forks

Repository files navigation

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, 2027 Ardan Labs

hello@ardanlabs.com

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] }}
  • Raw blocks: {% raw %}{{ literal text }}{% endraw %}
  • Filter blocks: {% filter replace('-', '_')|upper %}body{% endfilter %}
  • Tuple literals and unpacking assignments: {% set a, b = '001', '01' %}
  • Filtered and recursive loops, including loop.changed() and loop.depth0
  • Whitespace overrides: {%+ ... %} and {% ... +%}

Output follows Python's representations: none renders as None, booleans as True/False, and integral floats retain .0.

String and list repetition with * supports either operand order. Negative counts produce empty sequences. Each repetition is limited to 64 MiB of string bytes or list backing storage; larger results return a rendering error. This limit does not include nested values or the final rendered output.

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 · divisibleby · 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() · .title() · .capitalize() · .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
Beam-1.0-501B-A23B Beam
DeepSeek-V4-Flash DeepSeek V4
gemma-4-26B-A4B-it Gemma 4
GLM-5.2 GLM 5
gpt-oss-20b GPT-OSS
Inkling-2-Mini Inkling 2
Kimi-K3 Kimi K3
laguna Laguna
LFM2.5-VL-1.6B LFM2.5
Llama-3.2-1B-Instruct Llama 3.2
Ministral-3-14B-Instruct-2512 Mistral 3
Mistral-Medium-3.5-128B Mistral Medium 3.5
NVIDIA-Nemotron-3-Super-120B-A12B Nemotron 3
Qwen2-Audio-7B Qwen2-Audio
Qwen3-8B Qwen3
Qwen3-VL-30B-A3B-Instruct Qwen3-VL
Qwen3.5-35B-A3B Qwen3.5
Qwen3.6-35B-A3B Qwen3.6
rnj-1-instruct RNJ-1

Beam coverage includes XML tool-call arguments, parallel tool calls and replies matched by call ID, reasoning-effort options, and built-in versus custom bash tool definitions. The unmodified upstream template is included in the byte-for-byte comparisons against Python Jinja2. These tests validate template rendering, not model inference.

Inkling 2 coverage uses the unmodified template embedded in ggml-org/Inkling-2-Mini-GGUF/Inkling-2-Mini-Q8_0.gguf. It includes parallel tool calls and out-of-order replies matched by call ID, named assistant messages, reasoning-effort defaults and bounds, and image markers and unsupported audio. The template SHA-256 is 53a9035f3255945704b5857657cfb00c1165090c0641c4f782a0cbf268cc16dc.

Provisioning Compatibility Tests

The self-contained 5G network provisioning template lives separately in testdata/provisioning/5g-netprov.jinja. TestNetworkProvisioning renders it with an empty context, without loading chat requests or model-specific inputs. It also checks focused language cases and provisioning-specific boundary data.

The test uses scripts/render_provisioning.py and the same Python Jinja2 environment as the chat comparisons, including its custom tojson filter. Successful outputs must match byte-for-byte; expected error cases must fail in both engines. Each compiled Go template is rendered twice to check isolation. Python reference output is generated on demand rather than checked in.

Run it with uv installed:

go test . -run '^TestNetworkProvisioning$' -count=1 -v

License

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

About

Jinja template engine for Go programs

Resources

Stars

21 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages