How-to › Model, configure and generate

How to choose a template engine for generating source code#

Render one TypeScript class from one JSON model in Mustache, Handlebars, EJS, Nunjucks, Go text/template, and jostraca, and see where each one puts the logic.

Audience
Platform team
Level
beginner
Topic
Engineer templates and AST transforms
Languages
TypeScript and Go
Verified

Your generator renders a TypeScript client through Mustache, and the build fails on Promise<Page&lt;Book&gt;> because the engine escaped a generic type for HTML. Rewriting the template in EJS with raw <%- tags fixes that line and starts a slower failure: the method signatures are built by JavaScript inside the tags, where no unit test reaches them.

What you get

You will end up with one model rendered to the same TypeScript class by five engines and two jostraca modes, each checked byte for byte against a formatted reference. This is for you if you are picking the engine a code generator will live with.

Short answer

Choose a template engine by rendering one real file from one JSON model in Mustache, Handlebars, EJS, Nunjucks, and Go text/template, then diffing each result against a hand-written, Prettier-formatted reference. Mustache moves the logic into a precomputed view, EJS moves it into the template, and the other three split it with named helpers. Turn off HTML escaping in the four JavaScript engines, or List<T> comes out as List&lt;T&gt;.

You will need

Node 22 or later, Go 1.22 or later for the text/template row, and a small JSON model of what you generate. The sample’s model.json describes a Book client with four operations, seven parameters split across path, query, and body, and one paged result. That is enough for nested loops, a conditional import, and two levels of indentation. Prettier formats the reference at a print width of 100, and its --check flag holds the output to it.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
EJSThe team writes JavaScript and the template needs real expressionsLogic leaks into <% %> tags, where only a full render can test itPeople who should not edit code edit the templates
jostracaMost of the file is computed, or the template must stay valid TypeScriptNo template syntax at all, so the file’s shape lives in code until you run itThe output is mostly literal text a reviewer wants to read
MustacheThe template should read as a picture of its outputEvery derived value moves into a view, three fields for this one classNames have to be computed, joined, or checked
NunjucksJinja-style syntax, shared with a Python teamEscaping on by default, and a custom filter for anything the built-ins lackThe generator runs on Go or the JVM
oapi-codegen, Go text/templateA Go SDK whose templates you override by filenameIts README calls template overrides unstable, and says their input contexts keep driftingThe SDK is in any language but Go
Swagger Codegen, Handlebars templatesStock client templates in many languages, with a few overridesOne of its own stock templates escapes a type, and an override replaces a whole fileYou want one engine across generators you write yourself

Voxgig maintains jostraca, one of the six rows here, and it is not the recommendation.

The engine decides where the logic goes, not whether it exists. Mustache keeps templates dumb and testable by moving every derived value into a view, so even the comma between two parameters needs a field. EJS keeps the model raw and pays in templates that only a render can check. The two generators choose for you. Swagger Codegen runs Handlebars and oapi-codegen runs Go text/template.

Render one class from one model in every engine

reference/BookClient.ts was written by hand and formatted with Prettier. render.mjs sends model.json through each engine’s template, writes the results to rendered/, and compares bytes.

node render.mjs
engine               file                              same bytes as reference
Mustache             rendered/mustache.ts              yes
Handlebars           rendered/handlebars.ts            yes
EJS                  rendered/ejs.ts                   yes
Nunjucks             rendered/nunjucks.ts              yes
Go text/template     rendered/go-text-template.ts      yes
jostraca component   rendered/jostraca-component.ts    yes
jostraca fill-in     rendered/jostraca-fill-in.ts      yes

All seven reach the same bytes, so the choice rests on what each one asked for along the way. The Mustache template is the output with holes in it:

{{#ops}}

  /** {{method}} {{{path}}} */
  {{name}}({{#params}}{{name}}{{#optional}}?{{/optional}}: {{{type}}}{{^last}}, {{/last}}{{/params}}): Promise<{{{returns}}}> {
    return this.transport.call("{{method}}", "{{{path}}}", {
{{#groups}}
      {{key}}: { {{names}} },
{{/groups}}
    });
  }
{{/ops}}

It cannot join a list or compare two values, so view.mjs adds last to every parameter and groups to every operation before the render. The EJS template reads the raw model instead:

<% for (const op of ops) { -%>

  /** <%= op.method %> <%- op.path %> */
  <%= op.name %>(<%- op.params.map((p) => `${p.name}${p.optional ? '?' : ''}: ${p.type}`).join(', ') %>): Promise<<%- op.returns %>> {
    return this.transport.call("<%= op.method %>", "<%- op.path %>", {
<% for (const where of ['path', 'query', 'body']) { -%>
<%   const names = op.params.filter((p) => p.in === where).map((p) => p.name) -%>
<%   if (names.length > 0) { -%>
      <%= where %>: { <%= names.join(', ') %> },
<%   } -%>
<% } -%>

The signature is a map and a join inside an output tag. It needs no file beside the template, which is the attraction, and it has no test of its own.

Score where the logic ends up

score.mjs counts the control tags in each template, names the logic that lives outside it, and asks Prettier whether the template itself parses as TypeScript.

node score.mjs
engine               template            lines  logic tags  parses as TS  logic outside the template
Mustache             book.mustache          22           6  no            view adds anyPaged, groups, last
Handlebars           book.hbs               22           6  no            helpers groups, some
EJS                  book.ejs               25           5  no            none
Nunjucks             book.njk               25           8  no            filter namesIn
Go text/template     book.tmpl              25           7  no            funcs anyPaged, list, namesIn
jostraca fill-in     BookClient.frag.ts     10           2  yes           the methods, written as code
jostraca component   (none)                  0           0  n/a           the whole file

Handlebars, Nunjucks, and Go land in the middle. Their helpers are ordinary functions you can unit test, and the template calls them by name. Five of the six templates fail to parse, which means the formatter, the type checker and the editor’s outline cannot read them until they are rendered.

Fill in a file that stays TypeScript

jostraca has no template language. It writes a file from component calls, or fills marked regions of a file that is still valid source. The fill-in file here passes the Prettier check as it stands, because $$name$$Client is a legal identifier and the markers sit in comments:

// Generated from model.json. Do not edit.
import type { $$name$$ } from "./types";
// <[SLOT:imports]>
import type { Transport } from "./transport";

/** $$title$$ */
export class $$name$$Client {
  constructor(private readonly transport: Transport) {}
  // <[SLOT]>
}

The code that fills it decides the conditional import and writes the methods:

      Fragment({ from }, () => {
        // A marker keeps its own newline, so the text put at it has none. The Slot is
        // passed even when it is empty: a named marker with no Slot stays in the file.
        Slot({ name: 'imports' }, () => {
          if (m.ops.some((op) => op.paged === true)) Content('import type { Page } from "./page";')
        })
        Content(m.ops.flatMap((op) => methodLines(op)).join('\n'))
      })

Both rules in that comment come from the jostraca component reference. The second is the one that bites: leave out the Slot and // <[SLOT:imports]> reaches the output as text, where it compiles as a comment, so no build step reports it.

Check it worked

Run the formatter in check mode over the reference and every rendered file, then the tests.

npx prettier --check reference rendered
Checking formatting...
All matched files use Prettier code style!
node --test render.test.mjs
1..13
# tests 13
# suites 0
# pass 13
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 1113.47588

The first test renders all seven again and compares them with both the reference and the committed rendered/ files. Another feeds the comparison an empty file and a one-character change, and both fail it. A third misspells $$title$$ in the fill-in template, and the comparison refuses the result at line 6.

When it goes wrong

The generic type turns into entities. Mustache, Handlebars, and EJS escape for HTML on their default output tag. Nunjucks escapes because its autoescape option is on unless you turn it off, and escape.mjs leaves it at that default. Go’s html/template escapes too. The script renders one line each way:

node escape.mjs
default output tag
  Mustache          {{returns}}        Promise<Map&lt;string, Book[]&gt;>
  Handlebars        {{returns}}        Promise<Map&lt;string, Book[]&gt;>
  EJS               <%= returns %>     Promise<Map&lt;string, Book[]&gt;>
  Nunjucks          {{ returns }}      Promise<Map&lt;string, Book[]&gt;>
  Go html/template  {{.returns}}       Promise&lt;Map&lt;string, Book[]&gt;>
  Go text/template  {{.returns}}       Promise<Map<string, Book[]>>
  jostraca          $$returns$$        Promise<Map<string, Book[]>>

the fix
  Mustache          {{{returns}}}      Promise<Map<string, Book[]>>
  Handlebars        noEscape: true     Promise<Map<string, Book[]>>
  EJS               <%- returns %>     Promise<Map<string, Book[]>>
  Nunjucks          autoescape: false  Promise<Map<string, Book[]>>
  Go                text/template      Promise<Map<string, Book[]>>

book.mustache with double braces only:
  list(limit?: number, cursor?: string): Promise<Page&lt;Book&gt;> {
  prettier refused it: '>' expected. (11:57)

html/template also rewrote the < that the template text itself wrote. The text/template documentation sends HTML output to html/template, so source code belongs in text/template. The options are noEscape for Handlebars and autoescape for Nunjucks, which defaults to true.1 Keep the formatter in the pipeline, because it is the first thing to refuse the file.

A misspelled key renders as nothing. Mustache, Handlebars, and Nunjucks write an empty string, Go writes <no value>, and jostraca leaves $$retruns$$ in place, which its utilities reference calls deliberate:

node missing.mjs
the template asks for retruns; the model holds returns
  Mustache          default           Promise<>
  Handlebars        default           Promise<>
  Handlebars        strict: true      throws: "retruns" not defined in [object Object] - 1:10
  EJS               default           throws: retruns is not defined
  EJS               locals.retruns    Promise<>
  Nunjucks          default           Promise<>
  Nunjucks          throwOnUndefined  throws: attempted to output null or undefined value
  Go text/template  default           Promise<<no value>>
  Go text/template  missingkey=error  throws: template: line:1:10: executing "line" at <.retruns>: map has no entry for key "retruns"
  jostraca          default           Promise<$$retruns$$>

Turn on the strict mode where the engine has one. The Mustache manual says a missed variable returns an empty string, so only the comparison with the reference catches it there.

Fix the same escape in Swagger Codegen and oapi-codegen

A team that generates its SDK with either generator does not pick the engine. It overrides templates written for the engine the generator runs. generate.sh ran both once on the page’s openapi.json, and generators.mjs reads what they wrote.

node generators.mjs
Swagger Codegen 3.0.85, typescript-fetch
  Template engine: io.swagger.codegen.v3.templates.HandlebarTemplateEngine
  stock templates, api.ts:166   const needsSerialization = (<any>"Array&lt;string&gt;" !== ...
  -t override,     api.ts:166   const needsSerialization = (<any>"Array<string>" !== ...
  stock run: 9 files, -t run with only api.mustache: 9 files
  --template-engine mustache: exit status: 0, files written: 0

oapi-codegen v2.9.0, Go text/template
  stock typedef.tmpl:  // Book A title in the "catalog", returned as Array<Book> by listBooks & tagBook.
  user typedef.tmpl:   // Book was written by a user template.
  user.gen.go and indented.gen.go: identical, after oapi-codegen formatted both

Swagger Codegen’s stock typescript-fetch template writes {{dataType}} with two braces in one place, and the generated client carries the escaped type.2 The comparison still evaluates to true, so nothing breaks at run time. Fix it the documented way: copy the template into a folder, change it to three braces, and pass the folder with -t. The run with only api.mustache in the folder wrote the same nine files as the stock run, so the templates you do not copy fall back. Swagger Codegen’s generate --help also lists --template-engine mustache, which threw on this target, wrote no files, and exited 0.

oapi-codegen runs Go text/template, so the description keeps its <, & and quotes as written. Override a template by its exact filename under output-options.user-templates. It formats every file it writes, so a user template indented by eight to twelve spaces gave the same bytes as a tidy one.3

When not to do this

Do not run an engine bake-off when a generator already owns the templates. If Swagger Codegen or oapi-codegen writes your SDK, the engine is chosen, and the work is keeping overrides small. Swagger Codegen is the better fit when you need stock clients for many languages and can carry a few overrides. oapi-codegen is the better fit for a Go-only SDK, because its output arrives formatted without a separate step.

Do not use Go’s html/template for source code, and do not leave any of the four JavaScript engines on its default escaping.

Skip jostraca when the file is mostly literal text. A template is a picture a reviewer can read, and the component version moves that picture into code. jostraca earns its place when most of the file is computed, or when the template has to stay a file the formatter and the type checker can read.

Do not choose EJS for templates that people outside the generator’s code owners edit. The logic it allows has no test except the rendered file.

Last verified

Verified 2026-11-22 against Node 22.23.5, Go 1.24.7 and 1.25.0, mustache 4.2.0, handlebars 4.7.10, EJS 7.0.2, Nunjucks 3.2.4, prettier 3.10.1, jostraca 0.42.0, and shape 12.2.5. Every output block is what the command preceding it printed. Swagger Codegen 3.0.85 and oapi-codegen v2.9.0 each ran once, through generate.sh, and the files they wrote are committed under generated/; the page’s commands read those files and run neither generator. oapi-codegen v2.9.0 declares go 1.26.0, so the go command fetched a Go 1.26 toolchain to run it.

Footnotes

  1. The Nunjucks escape table in lib.js has six entries: the ampersand, both quotes, both angle brackets, and a backslash, which comes out as &#92;. Mustache, Handlebars, and EJS leave the backslash alone, and a test in the sample holds all four to that. Mustache and Handlebars escape the backtick, which closes a TypeScript template literal, and EJS and Nunjucks leave it alone. A generated Windows path in a string literal is the case where the sixth entry shows. ↩︎ Back to text

  2. Swagger Codegen’s documentation says it processes “handlebar templates with the Handlebars.java engine” and that -t points it at your own. The template this page overrides is api.mustache, which sits in a folder named handlebars in swagger-codegen-generators and is run by Handlebars whatever its extension says. The double-brace {{dataType}} is on line 231 of the master copy too. ↩︎ Back to text

  3. The formatting is imports.Process, called in codegen.go unless output-options.skip-fmt is set. The README that documents user templates also says template overrides are “always drifting and so are their input contexts” and calls them unstable. The formatter sits in the Go code that runs the templates, outside any file a user template replaces. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.