{"id":28719219,"url":"https://github.com/yetanotherchris/text-template","last_synced_at":"2026-03-11T13:38:51.235Z","repository":{"id":298314878,"uuid":"999563425","full_name":"yetanotherchris/text-template","owner":"yetanotherchris","description":"Go's text templating - a port of Go's text template package to C# via OpenAI Codex","archived":false,"fork":false,"pushed_at":"2025-10-03T19:02:04.000Z","size":382,"stargazers_count":0,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-12-16T18:59:49.745Z","etag":null,"topics":["dotnet","parser","template","text-template","text-templating-engine"],"latest_commit_sha":null,"homepage":"https://www.nuget.org/packages/go-text-template/","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yetanotherchris.png","metadata":{"files":{"readme":"docs/README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-06-10T12:50:14.000Z","updated_at":"2025-10-03T19:02:08.000Z","dependencies_parsed_at":null,"dependency_job_id":"3c2b483a-feb7-4f1d-a7fb-1af3ac391224","html_url":"https://github.com/yetanotherchris/text-template","commit_stats":null,"previous_names":["yetanotherchris/text-template"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/yetanotherchris/text-template","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yetanotherchris%2Ftext-template","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yetanotherchris%2Ftext-template/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yetanotherchris%2Ftext-template/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yetanotherchris%2Ftext-template/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yetanotherchris","download_url":"https://codeload.github.com/yetanotherchris/text-template/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yetanotherchris%2Ftext-template/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30382673,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-11T12:49:11.341Z","status":"ssl_error","status_checked_at":"2026-03-11T12:46:41.342Z","response_time":84,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dotnet","parser","template","text-template","text-templating-engine"],"created_at":"2025-06-15T06:00:46.704Z","updated_at":"2026-03-11T13:38:51.229Z","avatar_url":"https://github.com/yetanotherchris.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# text/template\n\n[![NuGet](https://img.shields.io/nuget/v/go-text-template.svg)](https://www.nuget.org/packages/go-text-template/)\n\ntext/template is a C# implementation of Go's template engine using ANTLR for parsing. It began as an experiment to see whether OpenAI Codex could port the Go implementation to .NET. Claude AI helped with explanations and refinements along the way, but the prompts were from my own knowledge of Antlr and grammars, and obviously C#.  \n\nIt ported the Go code to begin with, but then I realised Antlr would probably be a safer and more readable alternative than a straight Go ---\u003e C# port.\n\nThis README itself was also largely authored using Codex. Internally the engine uses an ANTLR-generated lexer and parser.\n\nThe original Go package can be found here:\n\n- https://pkg.go.dev/text/template#pkg-overview\n- https://cs.opensource.google/go/go/+/refs/tags/go1.24.4:src/text/template/template.go\n\nThis library now contains virtually all functionality from the original Go text/template package. \n\n## Usage\n\n```csharp\nvar tmpl = Template.New(\"hello\").Parse(\"Hello {{ .Name }}!\");\nvar result = tmpl.Execute(new { Name = \"World\" });\nConsole.WriteLine(result); // Hello World!\n```\n\n\n## Features\n\n- Replace `{{ variable }}` placeholders with values from dictionaries or model\n  objects.\n- Conditional blocks with `if`, `else if` and `else` clauses.\n- `for` loops and Go-style `range` loops over arrays, collections and maps.\n- Built-in functions: `eq`, `ne`, numeric comparisons (`lt`, `le`, `gt`, `ge`),\n  logical operators (`and`, `or`, `not`) supporting multiple arguments.\n- Basic pipelines with the `lower` function for transforming output, and `call` to invoke registered functions.\n- Declare variables with `{{ $name := value }}` and reference them later using `$name`.\n- Access nested properties, map keys and indexes, including dynamic indexing via\n  variables.\n- Whitespace trimming with `{{-` and `-}}` and comment syntax `{{/* ... */}}`.\n- Support for `with`, `define`, `template` and `block` directives.\n\n## Template reference\n\n```\n// -- 1. Variable Interpolation\n// Access properties\n{{ .Property }}\n\n// Nested property access\n{{ .User.Name }}\n\n// Index arrays or slices\n{{ .Items[0] }}\n\n// Access map entries\n{{ .Data.key }}\n\n// Control whitespace\n{{- .Name -}}\n// Declare and use a variable\n{{ $name := \"Hi there\" }}{{ $name }}\n\n// -- 2. Conditional Statements\n// Basic if blocks\n{{ if condition }}...{{ end }}\n\n// if/else blocks\n{{ if condition }}...{{ else }}...{{ end }}\n\n// else if chains\n{{ if condition }}...{{ else if other }}...{{ end }}\n\n// Supported conditions include\n{{ if .IsActive }}\n{{ if eq .Status \"active\" }}\n{{ if .User }}\n\n// -- 3. Loop Statements\n// Iterate slices or arrays\n{{ range .Items }}...{{ end }}\n\n// Capture index/value\n{{ range $i, $v := .Items }}...{{ end }}\n// Range with index/item variables\n{{ range $index, $item := .Items }}{{ $index }}: {{ $item }}{{ end }}\n\n// Iterate maps\n{{ range .Map }}...{{ end }}\n\n// Map key/value variables\n{{ range $k, $v := .Map }}...{{ end }}\n\n// Handle empty collections\n{{ range .Items }}...{{ else }}...{{ end }}\n\n// -- 4. Built-in Functions\n// Equality and inequality\n// eq, ne\n\n// Numeric comparisons\n// lt, le, gt, ge\n\n// Logical operators\n// and, or, not\n\n// Registered functions can be invoked via call\n{{ call \"Add\" 1 2 }}\n\nconst string template = \"{{ call \\\"Add\\\" 1 2 }}\";\nTemplate.RegisterFunction(\"Add\", new Func\u003cint, int, int\u003e((a, b) =\u003e a + b));\nvar result = Template.New(\"calc\").Parse(template).Execute(new {});\n// result == \"3\"\n\n// -- 5. Comments\n// Embedding comments\n{{/* comment */}}\n\n// -- 6. Pipelines\n// Chaining functions with |\n{{ .Name | lower }}\n\n// Available pipeline helpers include\n// lower - convert to lowercase\n// print - concatenate values using default formatting\n// printf - printf-style formatting using SprintfFormatter\n// html - HTML escape the value\n// js - JavaScript escape the value\n// urlquery - escape for URL query parameters\n// len - length of a collection or string\n// index - retrieve an element by index or key\n// slice - slice strings or lists\n// call - invoke a function value\n```\n\n### Example template usage\n\n```csharp\n// Define a named template using conditionals and a range loop\nstring tmpl = @\"\n{{ define \\\"letter\\\" }}\nDear {{ .Name }},\n{{ if .Attended }}\nIt was a pleasure to see you.\n{{ else }}\nSorry you couldn't make it.\n{{ end }}\nYou brought:\n{{ range .Items }}- {{ . }}\n{{ end }}\nThank you for the lovely {{ .Gift }}.\n{{ end }}\n{{ template \\\"letter\\\" . }}\";\n\n// Execute the template with a model\nvar output = Template.New(\"letter\").Parse(tmpl).Execute(new\n{\n    Name = \"Bob\",\n    Gift = \"toaster\",\n    Attended = false,\n    Items = new[] { \"book\", \"pen\" }\n});\n\n// Example output:\n// Dear Bob,\n// Sorry you couldn't make it.\n// You brought:\n// - book\n// - pen\n// Thank you for the lovely toaster.\nConsole.WriteLine(output);\n```\n\n### Template Definitions\n\n```csharp\nstring tmpl = @\"\n{{ define \\\"user\\\" }}\nName: {{ .Name }}\nAge: {{ .Age }}\n{{ end }}\n{{ template \\\"user\\\" . }}\";\nvar userResult = Template.New(\"user\").Parse(tmpl).Execute(new { Name = \"Jane\", Age = 42 });\n// userResult == \"Name: Jane\\nAge: 42\\n\"\n```\n\n### Calling Functions with `call`\n\n```csharp\nTemplate.RegisterFunction(\"Add\", new Func\u003cint, int, int\u003e((a, b) =\u003e a + b));\nstring callTmpl = \"{{ call \\\"Add\\\" 2 3 }}\";\nstring callResult = Template.New(\"calc\").Parse(callTmpl).Execute(new {});\n// callResult == \"5\"\n```\nSee the unit tests for more examples covering loops, conditionals and range expressions. The `YmlTemplateFileTest` shows how to render a full Kubernetes manifest from `tests/TestData/template.yml` with the expected output in `tests/TestData/expected.yml`.\n\n## Not Implemented Yet\n\n- Custom delimiter support.\n\n## Benchmark Results\n\nThe following benchmarks were run using [BenchmarkDotNet](https://benchmarkdotnet.org/) on .NET 9.0, `cpu: AMD Ryzen 7 5700X 8-Core Processor`. Each benchmark renders the same short template:\n\n```text\nHello {{ .Name }}! {{ range .Items }}{{ . }} {{ end }}\n```\n\n```bash\ndotnet run -c Release --project benchmarks/TextTemplate.Benchmarks -- --filter \"TemplateBenchmarks*\"\n```\n\nThe model contains five strings in the `Items` list so every engine performs a small loop. BenchmarkDotNet ran each test using its default configuration which executes a warm‑up phase followed by enough iterations (13–96 in our runs) to collect roughly one second of timing data. The Go implementation was benchmarked with `go test -bench .` using the equivalent template and data.\n\n| Method         | Mean        | Error     | StdDev    |\n|--------------- |------------:|----------:|----------:|\n| GoTextTemplate |    15.28 us |  0.238 us |  0.222 us |\n| Handlebars.net | 1,721.10 us | 29.683 us | 26.313 us |\n| Scriban        |    15.36 us |  0.304 us |  0.482 us |\n| DotLiquid      |    12.98 us |  0.162 us |  0.151 us |\n| Go text/template | 2,167 ns  | (505,638 iterations ) |\n\n### Advanced Scenario Benchmarks\n\nThe benchmark suite also includes `ComplexNestedTemplateBenchmarks`. This test\nloads the Kubernetes-style YAML templates found under `tests/TestData` and\nexecutes them as a single nested template. Run the .NET benchmarks with:\n\n```bash\ndotnet run -c Release --project benchmarks/TextTemplate.Benchmarks -- --filter \"ComplexNestedTemplateBenchmarks*\"\n```\n\nThe Go implementation can be benchmarked separately with:\n\n```bash\ngo test -bench BenchmarkGoComplexTemplate ./benchmarks/go -benchmem\n```\n\nExample results on a small container:\n\n| Method             | Mean        | Error     | StdDev    |\n|------------------- |------------:|----------:|----------:|\n| GoTextTemplate_NET |    172.0 us |   3.19 us |   2.98 us |\n| Handlebars.net     | 47,411.7 us | 679.98 us | 602.78 us |\n| Scriban            |    195.4 us |   3.07 us |   3.01 us |\n| DotLiquid          |    417.5 us |   6.07 us |   5.38 us |\n| Go text/template | 2,167 ns  | (1,218,702 iterations ) |\n\n## Claude's suggestions\nhttps://gist.github.com/yetanotherchris/c80d0fadb5a2ee5b4beb0a4384020dbf\n\n## License\n\nThis project is released under the MIT license. Source code was produced by\nOpenAI Codex with assistance from Claude.AI.\nThis README was written using OpenAI Codex.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyetanotherchris%2Ftext-template","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyetanotherchris%2Ftext-template","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyetanotherchris%2Ftext-template/lists"}