Jinja2С++

C++ implementation of the Jinja2 Python template engine. This library brings support of powerful Jinja2 template features into the C++ world, reports dynamic HTML pages and source code generation.
Introduction
Main features of Jinja2C++:
- Easy-to-use public interface. Just load templates and render them.
- Conformance to Jinja2 specification
- Full support of narrow- and wide-character strings both for templates and parameters.
- Built-in reflection for the common C++ types, nlohmann JSON and Boost.JSON.
- Powerful full-featured Jinja2 expressions with filtering (via ‘|’ operator) and ‘if’-expressions.
- Control statements (
set, for, if, filter, do, with).
- Templates extension, including and importing
- Macros
- Rich error reporting.
- Shared template environment with templates cache support
For instance, this simple code:
#include <jinja2cpp/template.h>
std::string source = R"(
{{ ("Hello", 'world') | join }}!!!
{{ ("Hello", 'world') | join(', ') }}!!!
{{ ("Hello", 'world') | join(d = '; ') }}!!!
{{ ("Hello", 'world') | join(d = '; ') | lower }}!!!
)";
Template tpl;
if (auto loaded = tpl.Load(source); !loaded)
std::cerr << loaded.error() << std::endl;
std::string result = tpl.RenderAsString({}).value();
produces the result string:
Helloworld!!!
Hello, world!!!
Hello; world!!!
hello; world!!!
Getting started
To use Jinja2C++ in your project you have to:
- Clone the Jinja2C++ repository
- Build it according to the instructions
- Link to your project.
Usage of Jinja2C++ in the code is pretty simple:
- Declare the jinja2::Template object:
jinja2::Template tpl;
- Populate it with template:
auto loaded = tpl.Load("{{ 'Hello World' }}!!!");
Load and Render return a jinja2::Result that holds the error when they fail, and
they are [[nodiscard]]: check the result (if (!loaded) std::cerr << loaded.error();)
rather than drop it.
- Render the template:
std::cout << tpl.RenderAsString({}).value() << std::endl;
and get:
Hello World!!!
That’s all!
More detailed examples and features description can be found in the documentation: https://jinja2cpp.github.io/docs/usage
Current Jinja2 support
Currently, Jinja2C++ supports the limited number of Jinja2 features. By the way, Jinja2C++ is planned to be a fully jinja2 specification-conformant. The current support is limited to:
- expressions. You can use almost every expression style: simple, filtered, conditional, and so on.
- the big number of filters (sort, default, first, last, length, max, min, reverse, unique, sum, attr, map, reject, rejectattr, select, selectattr, pprint, dictsort, abs, float, int, list, round, random, trim, title, upper, wordcount, replace, truncate, groupby, urlencode, capitalize, escape, tojson, striptags, center, xmlattr)
- the big number of testers (eq, defined, ge, gt, iterable, le, lt, mapping, ne, number, sequence, string, undefined, in, even, odd, lower, upper)
- the number of functions (range, loop.cycle)
- ‘if’ statement (with ‘elif’ and ‘else’ branches)
- ‘for’ statement (with ‘else’ branch and ‘if’ part support)
- ‘include’ statement
- ‘import’/‘from’ statements
- ‘set’ statement (both line and block)
- ‘filter’ statement
- ‘extends’/‘block’ statements
- ‘macro’/‘call’ statements
- ‘with’ statement
- ‘do’ extension statement
- recursive loops
- space control and ‘raw’/‘endraw’ blocks
Full information about Jinja2 specification support and compatibility table can be found here: https://jinja2cpp.github.io/docs/j2_compatibility.html.
Supported standards and compilers
Jinja2C++ requires C++17. C++17, C++20 and C++23 are supported and tested; C++26 is built
in CI as a forward-compatibility check. The CMake target requires cxx_std_17 publicly, so
CMake consumers get at least C++17 automatically; others need -std=c++17 (GCC up to 10,
Clang up to 15) or /std:c++17 (MSVC, whose default is still C++14). Version 1.x was the
last to support C++14.
Every pull request is built and tested with:
- Linux GCC 12 and 14, Clang 18 and 20: C++17, C++20, C++23 (C++26: GCC 14, Clang 20)
- macOS 15 and 26, Apple Clang: C++17, C++20, C++23
- Windows, MSVC 2022 x64: C++17, C++20, C++23 (
/std:c++latest until MSVC ships /std:c++23)
Build status
| Platform |
Status |
| Linux |
 |
| macOS |
 |
| Windows |
 |
Build and install
Jinja2C++ has three external dependencies:
Boost is used only by opt-in pieces: Boost.Multiprecision (with Boost.Config) for
-DJINJA2CPP_WITH_BIGINT=boost and the jinja2cpp/big_int/boost_cpp_int.h adapter, and
Boost.JSON for the jinja2cpp/binding/boost_json.h binding. The tests fetch what they check;
the library links no Boost and its core package never asks for it.
The JSON bindings and the big-integer adapter are header-only components of the package, each
bringing its own library (find_package(jinja2cpp COMPONENTS nlohmann_json) and
jinja2cpp::nlohmann_json, or pkg-config jinja2cpp-nlohmann_json); also boost_json and
boost_multiprecision. Every component is installed; see MIGRATION.md.
Why each dependency is needed, which are optional, and the CycloneDX and SPDX SBOMs installed with
the package: docs/dependencies.md.
To build and install Jinja2C++ you need CMake 3.23 or newer, Ninja (or another CMake
generator) and a C++17 compiler; see Supported standards and compilers.
git clone https://github.com/jinja2cpp/Jinja2Cpp.git
cmake -S Jinja2Cpp -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DJINJA2CPP_BUILD_TESTS=OFF
cmake --build build --parallel
cmake --install build --prefix <install folder>
The default internal dependencies mode downloads the pinned expected-lite, fmt and
fast_float and installs fmt and expected-lite next to the library; -DJINJA2CPP_DEPS_MODE=external
takes them from CMAKE_PREFIX_PATH instead (see Additional CMake build flags).
Leave out -DJINJA2CPP_BUILD_TESTS=OFF to build and run the tests (ctest --test-dir build),
which also fetches GoogleTest and nlohmann/json. A release source archive builds the same way
without Git; scripts/check_release_artifact.py checks that (docs/tasks/0225).
The install contains the license (MPL-2.0) and the notices of the third-party code the library
carries in share/doc/Jinja2Cpp/ (docs/licensing.md).
Moving from 1.x: MIGRATION.md lists every change and scripts/jinja2cpp_migrate.py
renames the deprecated 1.x names in your code.
Using the installed library
The install carries a CMake package and a pkg-config file. With CMake, point
CMAKE_PREFIX_PATH (or jinja2cpp_DIR) at the install folder and link the namespaced
target:
find_package(jinja2cpp 2 REQUIRED)
target_link_libraries(my_app PRIVATE jinja2cpp::jinja2cpp)
The target carries everything the library was built with: the include directories, the
C++17 floor, JINJA2CPP_LINK_AS_SHARED for a shared build, the expected-lite selection
and, for a static build, the library it depends on (fmt, installed next to it in the
default internal dependencies mode). The un-namespaced jinja2cpp target of
1.x still works. The install layout changed in 2.0: the package lives in
lib/cmake/jinja2cpp (was lib/jinja2cpp), the static library in lib (was
lib/static) and jinja2cpp.pc in lib/pkgconfig (was share/pkgconfig). Without CMake, use pkg-config --cflags --libs jinja2cpp
(--static for a static build).
Compatibility and versioning
- Names. The 1.x names that 2.0 could keep still compile, marked
[[deprecated]];
they are removed in 3.0.
- ABI across majors. Everything is declared in
jinja2::v2, an inline namespace: you
keep writing jinja2::Value, but the major version is part of every mangled name, so a
program compiled against 1.x headers fails to link with a 2.x library (static or shared)
instead of misbehaving at run time. Never spell v2 yourself. To declare Jinja2C++ types
without their definitions, include <jinja2cpp/fwd.h>: a hand-written
namespace jinja2 { class Value; } declares a different, undefined class and makes later
uses ambiguous. <jinja2cpp/jinja2cpp.h> includes the whole API except the JSON bindings.
If your code says using namespace jinja2; and has its own namespace-scope v2, qualify
one of them. Specialise the extension points inside namespace jinja2 { ... } or with their
qualified name (template<> struct jinja2::Reflector<MyType>). A 1.x-style
detail::Reflector specialisation must use the qualified form
(template<> struct jinja2::detail::Reflector<MyType>): MSVC does not look through the
inline namespace when namespace detail is reopened inside namespace jinja2, and declares
a second jinja2::detail instead.
- ABI within 2.x. The shared library’s SONAME carries the ABI version
(
libjinja2cpp.so.2, libjinja2cpp.2.dylib). It is bumped by any release that changes the
layout of a type you allocate (a Settings field, a Value alternative) or the signature
of an exported function, so a shared consumer is never loaded against an incompatible
library. A static consumer has no such guard and rebuilds after a minor upgrade; patch
releases keep the ABI.
Usage with conan.io dependency manager
ConanCenter’s jinja2cpp package is 1.3.2 at most; a 2.0 package is not published yet
(docs/tasks/0006), and its recipe declares the wrong license (MIT; Jinja2C++ is MPL-2.0, see
docs/licensing.md). Until then, Conan 2 can provide Jinja2C++'s
dependencies while you build it from source, as the conan-build CI job does:
conan profile detect # once, if there is no default profile
conan install . -of .conan --build=missing -s compiler.cppstd=17 -s build_type=Release
cmake -S . -B build-conan -G Ninja -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_TOOLCHAIN_FILE=.conan/conan_toolchain.cmake -DJINJA2CPP_DEPS_MODE=conan-build
cmake --build build-conan --parallel
cmake --install build-conan --prefix <install folder>
Then use the install as in Using the installed library.
Additional CMake build flags
You can define (via -D command-line CMake option) the following build flags:
- JINJA2CPP_BUILD_TESTS (default TRUE) - to build or not to Jinja2C++ tests.
- JINJA2CPP_STRICT_WARNINGS (default TRUE) - Enable strict mode compile-warnings(-Wall -Werror, etc).
- JINJA2CPP_HARDENING (default TRUE) - build the library with
-fstack-protector-strong, -fstack-clash-protection, -fcf-protection (x86) and -D_FORTIFY_SOURCE=3 (optimised configurations; 2 where the toolchain lacks 3), each only where the compiler knows it; MSVC gets /GS and /guard:cf. The flags apply to the library target only, not to the code that links it, and the CMake configure step prints the ones it applied. They trap on memory corruption only; none of them is the aborting _GLIBCXX_ASSERTIONS or _LIBCPP_HARDENING_MODE.
- JINJA2CPP_CONTRACT_CHECKS (default empty) - the engine’s own precondition and invariant checks (
src/contracts.h): OFF, ON (preconditions) or FULL (invariants too). A violation fails the render or load with an error result, it does not abort. Empty means FULL in Debug, sanitizer and fuzz builds and ON otherwise.
- JINJA2CPP_LANGUAGE_CONTRACTS (default FALSE) - with a C++26 compiler that has contracts (P2900), check with
contract_assert and install a violation handler that throws. The handler is program-global, so this stays opt-in. Without compiler support the option only warns.
- JINJA2CPP_MSVC_RUNTIME_TYPE (default /MD) - MSVC runtime type to link with (if you use Microsoft Visual Studio compiler).
- JINJA2CPP_DEPS_MODE (default “internal”) - modes for dependency handling. Following values possible:
internal In this mode Jinja2C++ build script uses dependencies shipped as subprojects. Nothing needs to be provided externally.
external-boost Deprecated, removed in 3.0: the same as internal, except that the opt-in Boost pieces (big-integer backend, adapter tests) take Boost from find_package.
external In this mode all dependencies should be provided externally. Paths to fmt, nonstd-* libs and, for the opt-in Boost pieces, boost should be specified via standard CMake variables (like CMAKE_PREFIX_PATH or libname_DIR)
conan-build Special mode for building Jinja2C++ via conan recipe.
- JINJA2CPP_TLS_INITIAL_EXEC (default TRUE for a shared library built against glibc, FALSE otherwise: musl refuses initial-exec thread-locals in a library loaded with
dlopen) - build the library’s thread-locals with the initial-exec TLS model (GCC/Clang). In position-independent code the default model reaches each thread-local through a call into the dynamic loader, which cost a shared library 5-20% of a render’s instructions. The thread-locals (about 660 bytes) then take part of the loader’s static TLS reserve; if a program loads the library with dlopen after other libraries used that reserve up, the load fails with “cannot allocate memory in static TLS block”, and building with FALSE avoids it. Set it for a static library linked into a shared module, such as the Python module.
- JINJA2CPP_TEST_BINDINGS (default
nlohmann_json) - the JSON bindings the tests check, a list of nlohmann_json and boost_json; it decides which JSON libraries the build fetches or finds. Every binding is installed as a package component whatever this lists.
- JINJA2CPP_WITH_BIGINT (default
none) - the big-integer backend every TemplateEnv starts with. With none, templates print, compare and convert integers of any size, and arithmetic whose result leaves int64_t fails with IntegerOutOfRange. With boost, that arithmetic is exact, as in Python, through Boost.Multiprecision’s cpp_int (header-only, compiled into the library; consumers need nothing). The installed package reports the choice as jinja2cpp_BIGINT (CMake) and bigint (pkg-config).
- JINJA2CPP_WITH_UNICODE_NAMES (default TRUE) - decode
\N{name} escapes in template string literals, as Python does, with a table of the Unicode 15.0 character names and aliases (about 450 KB of read-only data). With FALSE the table is left out and a \N{...} escape is a parse error.
Big integers
Python integers have no size limit. Jinja2C++ computes in int64_t and calls a big-integer backend only when a result leaves that range. A backend is a table of plain functions (jinja2cpp/big_int_backend.h), so one built separately plugs into a prebuilt library:
#include <jinja2cpp/big_int/boost_cpp_int.h> // needs the Boost.Multiprecision and Boost.Config headers
jinja2::TemplateEnv env;
env.SetBigIntBackend(jinja2::BoostCppIntBackend()); // or the library's built-in one, or your own
jinja2::Template tpl(&env);
tpl.Load("{{ 2 ** 100 }}"); // renders 1267650600228229401496703205376
jinja2cpp/big_int/boost_cpp_int.h is also the sample for writing a backend over another library. env.SetBigIntBackend(nullptr) turns big-integer arithmetic off for one environment.
Build with C++17 standard enabled
Jinja2C++ tries to use standard versions of std::variant, std::string_view and std::optional if possible.
Acknowledgments
Thanks to @flexferrum for creating this library, for being one of the brightest minds in software engineering community. Rest in peace, friend.
Thanks to @manu343726 for CMake scripts improvement, bug hunting, and fixing and conan.io packaging.
Thanks to @martinmoene for the perfectly implemented xxx-lite libraries.
Thanks to @vitaut for the amazing text formatting library.
Thanks to @martinus for the fast hash maps implementation.
Changelog
Unreleased
Breaking changes
-
Values print the way Python Jinja2 prints them (str()): booleans as True/False,
floats in shortest round-trip form with .0 on whole numbers (2.0, 0.30000000000000004,
1e+16), lists, tuples and dicts as [1, 'a'], (1, 2), {'a': 1} instead of nothing,
and join converts non-string items instead of dropping them. Templates that relied on
true/false or on 8-digit floats need updating. Integer % and ** now give integers (10 % 3 is 1, not 1.0).
-
jinja2::Value stores a C++ float as a float (its last alternative): IsFloat() and
AsFloat() read it, and IsDouble() is false for it, so code that read Value(1.5f) as a
double must test for both. A template sees the Python float its shortest digits name, so
12.123f prints 12.123 (not 12.123000144958496) and compares equal to 12.123; values
coming back from a template are double. Reflect keeps float members float.
-
A single newline at the end of a template is removed, as Jinja2 does by default; set
Settings::keepTrailingNewline to keep it. \r\n and \r in templates become \n, or
Settings::newlineSequence when set. trim_blocks now removes only a newline directly
after a tag (not spaces before it) and no longer applies after {% raw %}, and -%}
strips all following whitespace, several newlines included.
-
Tag delimiters and line statement/comment prefixes are configurable (Settings::variableStartString,
blockStartString, commentStartString, their ...EndString pairs, lineStatementPrefix,
lineCommentPrefix); set lineStatementPrefix = "#" for the old useLineStatements.
As in Jinja2, an end delimiter inside a string literal or open brackets does not end a tag
({{ {'a': {'b': 1}} }} parses), and a stray }}, %} or #} in text is text, not an error.
-
None and undefined are told apart. A jinja2::Value() (empty) in the context, in
globals or returned by a user callable is Python’s None: it prints as None and
is defined is true. A missing name, attribute or item is undefined and still prints
as nothing. undefined == none is now false, and the none test is available.
-
Undefined values follow Jinja2’s Undefined: printing, testing and iterating one is
fine (nope|length is 0), but an attribute, item or call of a missing name, or of a
missing attribute ({{ user.adress.city }}), is an error (ErrorCode::UndefinedError)
instead of rendering empty. Settings::undefinedPolicy selects Strict (any use but
is defined and default fails), Chainable (attributes of undefined stay undefined)
or Debug (prints {{ name }}), as Jinja2’s undefined option does.
-
Settings fields follow the camelBack naming: m_defaultMetadataType is
defaultMetadataType and extensions.Do is extensions.doStatement. useLineStatements
(use lineStatementPrefix = "#") and the unused jinja2CompatMode/Jinja2CompatMode are
removed. TemplateEnv keeps its state behind a pointer: its layout no longer changes when
it gains a member, templates keep that state alive (they may outlive the environment), and
the internal IsEqual, TimePoint and TimeStamp are gone. ApplyGlobals passes the
globals as const ValuesMap&. New: TemplateEnv::FromString (Jinja2 env.from_string),
AddTest/RemoveTest/FindTest for custom tests.
-
Macro bodies, {% call %} bodies, a recursive loop’s loop(...) and super() resolve
names where they are defined, as in Jinja2, not where they are called: a macro no longer
sees its caller’s loop variables or set names, and a call body sees the names around the
{% call %}, not the macro’s. A macro that read its caller’s loop variable should take it
as an argument: {% macro row(item) %}{{ item }}{% endmacro %}{% for item in items %}{{ row(item) }}{% endfor %}.
A macro or call body kept and called after the loop, macro call or include that defined it
has ended reads that frame’s names as undefined.
-
jinja2::ValuesMap keeps insertion order, like a Python dict: it is based on
jinja2::OrderedMap (jinja2cpp/utils/ordered_map.h) instead of std::unordered_map.
Iteration over a context dict, its repr ({{ d }}), items(), first, join and
xmlattr follow the order the C++ code inserted the keys, the same on every standard
library, and **kwargs handed to a user callable follow the call order. Dict reprs no
longer sort their keys; reflected structs still list theirs sorted. The map keeps the
std::unordered_map interface except the bucket API, node handles, hash_function,
key_eq and get_allocator, and no longer converts to std::unordered_map<std::string, Value>&.
The library’s SOVERSION is now 2.
-
jinja2::Reflect accepts nlohmann::ordered_json (nlohmann 3.9 and later), whose objects
keep document order; nlohmann::json objects iterate sorted, as before.
-
Boost is no longer a dependency of the library (docs/tasks/0230). The installed package
names no Boost in any dependencies mode: the internal mode no longer installs Boost’s
headers and libraries next to Jinja2C++, the installed CMake config no longer calls
find_dependency(Boost), and the exported target no longer defines
BOOST_SYSTEM_NO_DEPRECATED and BOOST_ERROR_CODE_HEADER_ONLY. A consumer that used the
Boost installed with Jinja2C++, or relied on those defines, must provide them itself. The
external-boost dependencies mode is deprecated (it now builds as internal), and Conan
builds use a header-only Boost.
Changes and improvements
- Boost.Regex is no longer a dependency, so external and Conan Boost builds need no compiled
regex library. The
JINJA2CPP_USE_REGEX CMake option is deprecated and ignored.
Version 1.3.2
What’s Changed
New Contributors
Version 1.3.1
Changes and improvements
- bump deps versions
- add new json binding - boost::json
- speedup regex parsing by switching to boost::regex(std::regex extremely slow)
- templates are now loading faster
Fixed bugs
- small fixes across code base
Breaking changes
- internal deps now used through cmake fetch_content
- default json serializer/deserializer is switched to boost::json
Version 1.2.1
Changes and improvements
- bump deps versions
- support modern compilers(up to Clang 12) and standards(C++20)
- tiny code style cleanup
Fixed bugs
- small fixes across code base
Breaking changes
- internal deps point to make based boost build
Version 1.1.0
Changes and improvements
batch filter added
slice filter added
format filter added
tojson filter added
striptags filter added
center filter added
xmlattr filter added
raw/endraw tags added
- repeat string operator added (e. g.
'a' * 5 will produce 'aaaaa')
- support for templates metadata (
meta/endmeta tags) added
-fPIC flag added to Linux build configuration
Fixed bugs
- Fix behavior of lstripblock/trimblocks global settings. Now it fully corresponds to the origina jinja2
- Fix bug with rendering parent
block content if child doesn’t override this block
- Fix compilation issues with user-defined callables with number of arguments more than 2
- Fix access to global Jinja2 functions from included/extended templates
- Fix point of evaluation of macro params
- Fix looping over the strings
- Cleanup warnings
Breaking changes
- From now with C++17 standard enabled Jinja2C++ uses standard versions of types
variant, string_view and optional
Version 1.0.0
Changes and improvements
default attribute added to the map filter (#48)
- escape sequences support added to the string literals (#49)
- arbitrary ranges, generated sequences, input iterators, etc. now can be used with
GenericList type (#66)
- nonstd::string_view is now one of the possible types for the
Value
filter tag support added to the template parser (#44)
escape filter support added to the template parser (#140)
capitalize filter support added to the template parser (#137)
- the multiline version of
set tag added to the parser (#45)
- added built-in reflection for nlohmann JSON and RapidJSON libraries (#78)
loop.depth and loop.depth0 variables support added
- {fmt} is now used as a formatting library instead of iostreams
- robin hood hash map is now used for internal value storage
- rendering performance improvements
- template cache implemented in
TemplateEnv
- user-defined callables now can accept global context via
*context special param
- MinGW, clang >= 7.0, XCode >= 9, gcc >= 7.0 are now officially supported as a target compilers (#79)
Fixed bugs
- Fixed pipe (
|) operator precedence (#47)
- Fixed bug in internal char <-> wchar_t converter on Windows
- Fixed crash in parsing
endblock tag
- Fixed scope control for
include and for tags
- Fixed bug with macros call within expression context
Breaking changes
- MSVC runtime type is now defined by
JINJA2CPP_MSVC_RUNTIME_TYPE CMake variable
Version 0.9.2
Major changes
Minor changes
- Render-time error handling added
- Dependency management mode added to the build script
- Fix bugs with error reporting during the parse time
- Upgraded versions of external dependencies
Breaking changes
RenderAsString method now returns nonstd::expected instead of regular std::string
- Templates with
import, extends and include generate errors if parsed without TemplateEnv set
- Release bundles (archives) are configured with
external dependency management mode by default
Version 0.9.1
applymacro filter added which allows applying arbitrary macro as a filter
- dependencies to boost removed from the public interface
- CMake scripts improved
- Various bugs fixed
- Improve reflection
- Warnings cleanup
Version 0.9
- Support of ‘extents’/‘block’ statements
- Support of ‘macro’/‘call’ statements
- Rich error reporting
- Support for recursive loops
- Support for space control before and after control blocks
- Improve reflection
Version 0.6
评论