Home › Developer Tools › Jinja2 Template Tester

Jinja2 Template Tester

Paste a Jinja2 template and its variables in YAML or JSON and see the rendered result as you type. It runs the real Jinja2 library (Python, via Pyodide) inside your browser, so whitespace, filters and error messages match what you get in Ansible, Flask or Salt.

Last updated:

Environment
Ctrl + Enter renders

        
        
Advertisement
Advertisement

How to use the Jinja2 Template Tester

  1. Pick an example or paste your template into the Template box (for example an Ansible .j2 file).
  2. Enter the variables as YAML or JSON in the Variables box. The top level must be key: value pairs.
  3. Choose the flavor: Plain Jinja2, Ansible (extra filters, strict undefined, trim_blocks) or Flask (autoescape).
  4. Read the output. It updates as you type; turn on Show whitespace to see stray spaces and blank lines.
  5. Fix any error using the highlighted line number and hint, then copy or download the rendered text.

Jinja2 syntax at a glance

SyntaxWhat it doesExample
{{ … }}Print an expression{{ user.name | upper }}
{% … %}Statement: if, for, set, macro, block{% if port == 443 %}ssl{% endif %}
{# … #}Comment, not printed{# TODO: add IPv6 #}
{%- … -%}Strip whitespace before / after the tag{%- for x in xs -%}
| filterTransform a value, filters can be chained{{ hosts | sort | join(', ') }}
is testCheck a value{% if port is number %}, is defined
loop.*Loop helpers inside forloop.index, loop.first, loop.last, loop.cycle('a','b')
namespace()Keep a value that changes inside a loop{% set ns = namespace(total=0) %}
~Join values as strings{{ 'v' ~ version }}

Useful built-in filters

FilterExampleResult
default{{ port | default(8080) }}8080 when port is undefined
join{{ ['a','b'] | join('-') }}a-b
map / selectattr{{ users | selectattr('active') | map(attribute='name') | list }}names of active users
groupby{% for k, items in rows | groupby('region') %}rows grouped by region
dictsort{% for k, v in cfg | dictsort %}dictionary items sorted by key
format{{ '%.2f' | format(3.14159) }}3.14
indent{{ block | indent(4) }}indents every line after the first by 4 spaces
tojson{{ data | tojson }}HTML-safe JSON for scripts
truncate / wordcount{{ text | truncate(20) }}shortened text ending in ...

Tips for debugging templates

  • Turn on strict undefined while testing. A misspelled variable then raises an error with its line number instead of printing nothing.
  • Watch out for dict method names. Keys called items, keys, values or get must be read with brackets: data['items'].
  • Variables set inside a loop do not survive the loop. Use namespace() for counters and totals.
  • Use | int or | float before math on values that come from YAML strings or Ansible facts.
  • Only mark trusted HTML as safe. With autoescape on, | safe prints raw HTML, which can let untrusted input inject markup.

Frequently asked questions

Is this the real Jinja2 or a JavaScript imitation?

It is the real Jinja2 Python library. The page loads Pyodide, a build of Python for the browser, together with the official Jinja2 and PyYAML packages, and renders your template with them. The first load downloads about 10 MB from a public CDN; after that your browser caches it. Your template and variables never leave your device.

Can I test Ansible templates here?

Yes. Choose the Ansible flavor: it turns on trim_blocks and keep_trailing_newline like the template module, makes undefined variables an error, and adds common Ansible filters such as to_nice_yaml, to_json, regex_replace, regex_search, combine, dict2items, ternary, bool, b64encode, basename and flatten. Ansible lookups, facts and plugins are not available, so define facts like ansible_hostname yourself in the variables.

Why does my output have extra blank lines?

Every {% … %} tag leaves the newline that follows it. Turn on trim_blocks to remove the first newline after a block tag, lstrip_blocks to remove indentation before it, or add a minus sign inside the tag, as in {%- if x -%}, to strip whitespace on that side. Show whitespace marks spaces with dots and line ends with ¶.

What happens with undefined variables?

With the default setting an undefined variable renders as an empty string, which can hide typos. Strict raises an UndefinedError with the line number, as Ansible does. Chainable lets you write a.b.c on missing values without errors, and Debug prints the placeholder, for example {{ missing_var }}. The chips under the output list each variable the template uses and mark the ones you have not defined.

Why do I get 'builtin_function_or_method' object is not iterable?

Your data has a key named items, keys or values, and order.items finds the Python dict method instead of your list. Write order['items'] instead, or rename the key. The same applies to other dict method names such as update, get or pop.

Why is YAML yes or on turned into true?

The variables are read with PyYAML, which follows YAML 1.1, the same rules Ansible uses. In YAML 1.1 yes, no, on and off are booleans. Quote the value ("yes") if you need the text.

Does it support macros, includes and template inheritance?

Macros, call blocks, filters, tests, loops with loop.index, set with namespace(), do and break/continue all work in the single template you test. include, import and extends need other template files, which this tester does not have, so put macros in the same template or paste the parent template's content in.

Are all the tools on FreeToolCabin tested for quality and accuracy?

Yes! Every tool on our site undergoes automated Q/A testing in real browser environments to ensure high precision, correct output, and zero errors. If you happen to spot a bug or have a suggestion, please contact us at [email protected] and our team will review it right away.

Related tools

YAML Validator & FormatterValidate, format and minify YAML, and convert YAML to JSON or back.Online Python CompilerRun Python 3 in your browser with input(), numpy, pandas, charts and share links.YAML to JSON ConverterConvert YAML to pretty or minified JSON, with errors pinned to the exact line.Nginx Config GeneratorBuild an nginx server block: static site, SPA, reverse proxy or PHP, with SSL, gzip and redirects.QR Code GeneratorMake QR codes for links, Wi-Fi, email and more.Barcode GeneratorCreate Code 128, EAN-13, UPC-A, EAN-8, Code 39 and ITF-14 barcodes as PNG or SVG.UUID GeneratorGenerate UUID v4 and v7 / GUIDs in bulk and copy or download them.Schema Markup Generator (JSON-LD)Create JSON-LD structured data for FAQ, Product, Article and more.Htaccess & Nginx Redirect GeneratorBuild 301 redirects for .htaccess, Nginx and Netlify or Cloudflare _redirects.Fake Data GeneratorGenerate mock data as JSON, CSV or SQL.Random String GeneratorGenerate secure random strings and tokens in bulk with any length and character set.API Key GeneratorCreate secure API keys and secrets with prefixes, checksums and SHA-256 hashes for storage.MIME Type LookupFind the MIME type for any file extension, or the extensions for a MIME type, in 400+ entries.Cron Expression GeneratorBuild crontab schedules visually, read them in plain English and see the next run times.URL Slug GeneratorTurn titles into clean, SEO-friendly URL slugs: accents, stop words, separators and bulk lines.JSON Schema GeneratorTurn sample JSON into a draft 2020-12 JSON Schema with types, required fields and formats.Gitignore GeneratorBuild a .gitignore from 50+ templates for languages, frameworks, IDEs and OS, merged and deduped.License GeneratorCreate a LICENSE file for MIT, Apache, GPL, BSD, ISC, MPL or Unlicense with your name and year.ULID GeneratorGenerate sortable ULIDs and UUID v7 in bulk, monotonic option, and decode their timestamps.Htpasswd GeneratorCreate .htpasswd entries with bcrypt, APR1-MD5 or SHA-1 for Apache and Nginx basic auth.Placeholder Image GeneratorCreate placeholder images in any size, color and text as PNG, JPG, WebP, SVG or data URI.Ads.txt GeneratorCreate or validate ads.txt and app-ads.txt files: seller lines, cert IDs and variables.Docker Run to Compose ConverterConvert docker run commands to docker-compose.yml, or a compose file back to docker run.Dockerfile GeneratorGenerate a production Dockerfile and .dockerignore for Node, Python, Go or a static nginx site.HTML Boilerplate GeneratorTick the options you need and get a clean HTML5 starter template with meta, OG tags and CSS reset.JSON to Zod SchemaInfer a Zod (or Yup) schema from sample JSON with optional, nullable and z.infer types.Linux Commands Cheat SheetSearchable Linux and bash command reference with flags explained, examples and copy buttons.LLMs.txt GeneratorBuild an llms.txt file for AI crawlers: summary and link sections, import from your sitemap.Nano ID GeneratorGenerate secure Nano IDs with custom alphabet, length and count, plus a collision calculator.OpenAPI / Swagger ViewerView OpenAPI 2/3 JSON or YAML as interactive API docs with validation and an endpoint list.package.json GeneratorFill a form and get a valid, npm-ready package.json with scripts, dependencies and checks.PKCE Code Challenge GeneratorGenerate an OAuth 2.0 PKCE code_verifier and S256 code_challenge, build auth URLs, verify pairs.README GeneratorFill in a form and get a polished README.md with badges, install, usage and license, live preview.Regex GeneratorBuild regular expressions visually from blocks or presets (email, date, phone) and test them live.Commit Message GeneratorBuild Conventional Commit messages with type, scope, body, breaking change and issue refs.Database Schema DesignerDesign tables and relationships visually, then export SQL for MySQL, PostgreSQL or SQLite.Docker Compose GeneratorBuild a docker-compose.yml with a form: services, ports, volumes, env, healthchecks and presets.Dummy File GeneratorCreate test files of an exact size in KB, MB or GB with zeros, random bytes or text.HowTo Schema GeneratorCreate HowTo JSON-LD with steps, tools, supplies, total time and cost, then copy it.Htaccess GeneratorBuild an Apache .htaccess file: HTTPS, www, gzip, caching, error pages, IP blocks, hotlinks.HTML Email Template BuilderDrag and drop blocks to build a responsive, table-based HTML email with inline styles.Organization Schema GeneratorCreate Organization JSON-LD with logo, URL, contact points, address and social profiles.PIN GeneratorGenerate random 4, 6 or 8-digit PINs that avoid sequences, repeats, dates and common PINs.Product Schema GeneratorBuild Product JSON-LD with price, availability, brand, GTIN, ratings and reviews.Question Keyword GeneratorFind the questions people ask about a topic, grouped by who, what, why, how, can and more.Recipe Schema GeneratorCreate Recipe JSON-LD with ingredients, steps, prep and cook times, nutrition and ratings.Security Headers GeneratorPick HSTS, CSP, frame, referrer and permissions options and get Apache, Nginx, Netlify or Cloudflare config.SKU GeneratorBuild consistent SKUs from brand, category, size and color, then export every variant as CSV.Typography Scale GeneratorBuild a modular type scale from a base size and ratio, then copy CSS variables or a Tailwind config.WordPress Salt GeneratorGenerate fresh WordPress security keys and salts for wp-config.php, .env or Docker in one click.ANSI Color Code GeneratorStyle terminal text with 16, 256 or RGB colors and get escape codes for bash, Python, JS and C.Apache Virtual Host GeneratorCreate an Apache VirtualHost config with SSL, redirects, reverse proxy or PHP-FPM in seconds.Bash Prompt GeneratorDrag and drop a custom PS1 prompt for bash or zsh with colors, git branch and a live preview.Changelog GeneratorTurn Conventional Commit messages into a grouped Keep a Changelog Markdown file per version.cURL Command BuilderBuild curl commands from a form: method, headers, query, JSON or form body, auth and flags.Docker Compose to KubernetesConvert docker-compose.yml into Kubernetes Deployment, Service, ConfigMap and PVC manifests.Docker Compose ValidatorCheck a docker-compose.yml for YAML errors, schema mistakes, broken references and deprecated keys.Dockerfile LinterLint a Dockerfile for best practices: pinned tags, apt cleanup, non-root USER and layer count.Dockerignore GeneratorBuild a .dockerignore from Node, Python, Go and Java templates, plus your own entries.ESLint Config GeneratorGenerate a flat eslint.config.js for JavaScript, TypeScript, React or Node with rule presets.Git Branch Name GeneratorTurn a ticket ID and title into a clean, valid git branch name like feature/PROJ-12-add-login.GitLab CI Config GeneratorGenerate a .gitlab-ci.yml with stages, jobs, images, cache, artifacts and rules from templates.JSON Schema Mock Data GeneratorGenerate realistic sample JSON from a JSON Schema: formats, patterns, $ref, seeds and counts.Kubernetes Secret GeneratorCreate Kubernetes Secret YAML from key/value pairs or .env with auto base64, or decode one.Kubernetes YAML ValidatorValidate Kubernetes manifests against the API schema of a chosen version, with error paths.Prettier Config GeneratorToggle Prettier options, preview formatted code live and copy your .prettierrc file.Quartz Cron GeneratorBuild and explain Quartz and Spring cron expressions with seconds, ?, L, W and #, plus next fire times.README Badge GeneratorCreate Shields.io-style README badges for license, version, build and custom labels.
See all 85 Code Generators & Builders →