@telga/gotpl
v0.1.1
Published
A Go-style server-side HTML template engine for Bun and Node.js
Maintainers
Readme
gotpl
Go-style server-side HTML templates for Bun and Node.js.
gotpl is designed to render existing Go-style templates without changing the template files:
import gotpl from "@telga/gotpl";
const templates = gotpl.parseFiles(
"./views/common.html",
"./views/home.html",
);
const html = templates.execute("/", {
Title: "Home",
Items: ["one", "two"],
});Supported template syntax
defineandtemplateinclusionif,else, andelse ifrange, includingelseand range variableswith- Dot and nested field access such as
.User.Name $variables and pipelines- Common built-ins including
eq,ne,len,index,slice,printf,print,call,html,js, andurlquery - Go-style comments and whitespace trimming
- Context-sensitive escaping for HTML text, attributes, URLs, JavaScript, and CSS
parseFiles is synchronous, matching the simple local-file workflow of Go's ParseFiles. Parsing happens once; a TemplateSet can be reused for many requests.
For one-off templates, use parse:
import { parse } from "@telga/gotpl";
const template = parse("<h1>{{ .Title }}</h1>");
const html = template.execute({ Title: "Home" });For file-based routes, parseGlob wraps each matched file as a named template. Paths are relative to the glob base; index.html maps to /, and nested index files retain their trailing slash:
import { parseGlob } from "@telga/gotpl";
const templates = parseGlob("views/**/*.html");
templates.execute("/", { Title: "Home" });
templates.execute("/admin/", { Title: "Admin" });Bun usage
import gotpl from "@telga/gotpl";
const templates = gotpl.parseFiles("views/common.html", "views/app.html");
Bun.serve({
fetch(request) {
const html = templates.execute(new URL(request.url).pathname, {
Title: "Dashboard",
});
return new Response(html, {
headers: { "content-type": "text/html; charset=utf-8" },
});
},
});Security model
Template source should be trusted application code. Do not load arbitrary user-provided templates.
Interpolated values are escaped according to their HTML context. Unsafe URL schemes and event-handler attributes are rejected. The html built-in intentionally creates an unescaped value and should only be used with trusted HTML.
This project aims for practical compatibility with Go-style templates; it is not a byte-for-byte implementation of every behavior in Go's html/template package.
Development
bun install
bun test
bun run buildThe package build emits dist/index.js and the published package contains only the compiled module, type declarations, and README.
