Our Jinja2 rendering engine is fast (C++ based), and uses the Godot resource system.
Here is a simple example. We set up an environment, similar to the 'real' Jinja2 over at Python, we obtain the template, and call render()
with some parameters passed as Dictionary
.
@onready var JINJA_ENV: Jinja2Environment = Jinja2Environment.new()
func _ready():
JINJA_ENV.set_base_directory("res://web/test/")
var tmpl: Jinja2Template = JINJA_ENV.get_template("hello.jinja2")
var params: Dictionary = {
"title": "Hello World",
"foo": true,
"bar": {
"items": ["hi!", 2]
},
"vec": Vector2(2.5, 4.3),
"num": 5.5
}
var html: String = tmpl.render(params)
print(html)
hello.jinja2
Our template looks like this:
<html>
<body>
<h1>{{ title }}</h1>
{% if foo %}
<p>foo was true</p>
{% else %}
<p>foo was false</p>
{% endif %}
<ul>
{% for val in bar.items %}
<li>{{ val }}</li>
{% endfor %}
</ul>
<ul>
<li>num: {{ num + 0.7 }}</li>
<li>vector: {{ vec.x | round(2) }}, {{ vec.y | round(2) }}</li>
</li>
</body>
</html>
<html>
<body>
<h1>Hello World</h1>
<p>foo was true</p>
<ul>
<li>hi!</li>
<li>2</li>
</ul>
<ul>
<li>num: 6.2</li>
<li>vector: 2.5, 4.3</li>
</ul>
</body>
</html>
If you have a WebView
node around, you can call $WebView.load_html(html, url)
, where
html
is the generated HTML, and URL is used to resolve relative
URLs in the document (such as referenced images or stylesheets), e.g: res://godot/web/test/
.
render()
function, the key(s)
should always be of string type. This is also the case for any nested Dictionaries.