typed and compiled template engine inspired by jinja2, twig and onionhammer/nim-templates for Nim.
# https://github.com/enthus1ast/dekao/blob/master/bench.nim
# nim c --gc:arc -d:release -d:danger -d:lto --opt:speed -r bench.nim
name ................. min time avg time std dv runs
dekao ................ 0.105 ms 0.117 ms ±0.013 x1000
karax ................ 0.126 ms 0.132 ms ±0.008 x1000
htmlgen .............. 0.021 ms 0.023 ms ±0.004 x1000
nimja ................ 0.016 ms 0.017 ms ±0.001 x1000 <--
nimja iterator ....... 0.008 ms 0.009 ms ±0.001 x1000 <--
scf .................. 0.023 ms 0.024 ms ±0.003 x1000
nim-mustache ......... 0.745 ms 0.790 ms ±0.056 x1000
server.nim
import asynchttpserver, asyncdispatch
import nimja/parser
import os, random # os and random are later used in the templates, so imported here
type
User = object
name: string
lastname: string
age: int
proc renderIndex(title: string, users: seq[User]): string =
## the `index.nimja` template is transformed to nim code.
## so it can access all variables like `title` and `users`
## the return variable could be `string` or `Rope` or
## anything which has a `&=`(obj: YourObj, str: string) proc.
compileTemplateFile("index.nimja", baseDir = getScriptDir())
proc main {.async.} =
var server = newAsyncHttpServer()
proc cb(req: Request) {.async.} =
# in the templates we can later loop trough this sequence
let users: seq[User] = @[
User(name: "Katja", lastname: "Kopylevych", age: 32),
User(name: "David", lastname: "Krause", age: 32),
]
await req.respond(Http200, renderIndex("index", users))
server.listen Port(8080)
while true:
if server.shouldAcceptRequest():
await server.acceptRequest(cb)
else:
poll()
asyncCheck main()
runForever()
index.nimja:
{% extends partials/_master.nimja%}
{#
extends uses the master.nimja template as the "base".
All the `block`s that are defined in the master.nimja are filled
with blocks from this template.
If the templates extends another, all content HAVE TO be in a block.
blocks can have arbitrary names
extend must be the first token in the template,
only comments `{# Some foo #}` and strings are permitted to come before it.
#}
{% block content %}
{# A random loop to show off. #}
{# Data is defined here for demo purpose, but could come frome database etc.. #}
<h1>Random links</h1>
{% const links = [
(title: "google", target: "https://google.de"),
(title: "fefe", target: "https://blog.fefe.de")]
%}
{% for (ii, item) in links.pairs() %}
{{ii}} <a href="https://github.com/enthus1ast/nimja/blob/master/{{item.target}}">This is a link to: {{item.title}}</a><br>
{% endfor %}
<h1>Members</h1>
{# `users` was a param to the `renderIndex` proc #}
{% for (idx, user) in users.pairs %}
<a href="https://github.com/enthus1ast/nimja/blob/master/users/{{idx}}">{% importnimja "./partials/_user.nimja" %}</a><br>
{% endfor %}
{% endblock %}
{% block footer %}
{#
we can call arbitraty nim code in the templates.
Here we pick a random user from users.
#}
{% var user = users.sample() %}
{#
imported templates have access to all variables declared in the parent.
So `user` is usable in "./partials/user.nimja"
#}
This INDEX was presented by.... {% importnimja "./partials/_user.nimja" %}
{% endblock footer %} {# the 'footer' in endblock is completely optional #}
master.nimja
{#
This template is later expanded from the index.nimja template.
All blocks are filled by the blocks from index.nimja
Variables are also useable.
#}
<html>
<head>
<title>{{title}}</title>
</head>
<body>
<style>
body {
background-color: aqua;
color: red;
}
</style>
{# The master can declare a variable that is later visible in the child template #}
{% var aVarFromMaster = "aVarFromMaster" %}
{# We import templates to keep the master small #}
{% importnimja "partials/_menu.nimja" %}
<h1>{{title}}</h1>
{# This block is filled from the child templates #}
{%block content%}{%endblock%}
{#
If the block contains content and is NOT overwritten later.
The content from the master is rendered
#}
{% block onlyMasterBlock %}Only Master Block{% endblock %}
<footer>
{% block footer %}{% endblock %}
</footer>
</body>
</html>
partials/_menu.nimja:
<a href="https://github.com/enthus1ast/nimja/blob/master/">index</a>
partials/_user.nimja:
User: {{user.name}} {{user.lastname}} age: {{user.age}}
{{ myObj.myVar }}
--transformed-to---> $(myObj.myVar)
myExpression.inc()
nimja transforms templates to nim code on compilation, so you can write arbitrary nim code.
proc foo(ss: string, ii: int): string =
compileTemplateStr(
"""example{% if ii == 1%}{{ss}}{%endif%}{% var myvar = 1 %}{% myvar.inc %}"""
)
is transformed to:
proc foo(ss: string; ii: int): string =
result &= "example"
if ii == 1:
result &= ss
var myvar = 1
inc(myvar, 1)
this means you have the full power of nim in your templates.
there are only three relevant procedures:
compileTemplateStr(str: string)
compiles a template string to nim astcompileTemplateFile(path: string)
compiles the content of a file to nim astgetScriptDir()
returns the path to your current project, on compiletime.compileTemplateFile
transforms the given file into the nim code.
you should use it like so:
import os # for `/`
proc myRenderProc(someParam: string): string =
compileTemplateFile("myFile.html", baseDir = getScriptDir())
echo myRenderProc("test123")
compileTemplateFile
can also generate an iterator body, for details look at the
iteratior section.
compileTemplateFile
(also compileTemplateString
) generates the body of a proc/iterator so it generates
assign calls to a variable. The default is result
.
If you want it to use another variable set it in varname
also look at:
compileTemplateStr
compiles the given string into nim code.
proc myRenderProc(someParam: string): string =
compileTemplateStr("some nimja code {{someParam}}", baseDir = getScriptDir())
echo myRenderProc("test123")
compileTemplateStr
can also generate an iterator body, for details look at the
iteratior section.
compileTemplateString
(also compileTemplateFile
) generates the body of a proc/iterator so it generates
assign calls to a variable. The default is result
.
If you want it to use another variable set it in varname
baseDir
is needed when you want to import/extend templates!
A context can be supplied to the compileTemplateString
(also compileTemplateFile
), to override variable names:
block:
type
Rax = object
aa: string
bb: float
var rax = Rax(aa: "aaaa", bb: 13.37)
var foo = 123
proc render(): string =
compileTemplateString("{{node.bb}}{{baa}}", {node: rax, baa: foo})
Please note, currently the context cannot be procs/funcs etc.
also look at:
{% if aa == 1 %}
aa is: one
{% elif aa == 2 %}
aa is: two
{% else %}
aa is something else
{% endif %}
when
is the compile time if statement.
It has the same semantic than if
{% when declared(isDeclared) %}
isDeclared
{% elif true == true %}
true
{% else %}
something else
{% endwhen %}
(Since Nimja 0.8.1)
case
has the same semantic as the nim case statement.
Use case
for example if you want to make sure that all cases are handled.
If not all cases are covered, an error is generated.
{%- case str -%}
{%- of "foo" -%}
foo
{%- of "baa" -%}
baa
{%- of "baz" -%}
baz
{%- else -%}
nothing
{%- endcase -%}
compileTemplateStr
and compileTemplateFile
both need a surrounding proc.
tmpls
(template str) and tmplf
(template file) are a shorthand for these
situations where you want to inline a render call.
let leet = 1337
echo tmpls("foo {{leet}}")
echo tmplf("templates" / "myfile.nimja", baseDir = getScriptDir())
A context can be supplied to the template, to override variable names:
block:
type
Rax = object
aa: string
bb: float
var rax = Rax(aa: "aaaa", bb: 13.37)
var foo = 123
tmpls("{{node.bb}}{{baa}}", {node: rax, baa: foo})
Please note, currently the context cannot be procs/funcs etc.
{% for (cnt, elem) in @["foo", "baa", "baz"].pairs() %}
{{cnt}} -> {{elem}}
{% endfor %}
{% for elem in someObj.someIter() %}
{# `elem` is accessible from the "some/template.nimja" #}
{# see importnimja section for more info #}
{% importnimja "some/template.nimja" %}
{% endfor %}
{% while isTrue() %}
still true
{% endwhile %}
{% var idx = 0 %}
{% while idx < 10 %}
still true
{% idx.inc %}
{% endwhile %}
{# single line comment #}
{#
multi
line
comment
#}
{# {% var idx = 0 %} #}
declare your own $
before you call
compileTemplateStr()
or compileTemplateFile()
for your custom objects.
For complex types it is recommend to use the method described in the importnimja
section.
{{myVar}}
{{someProc()}}
import the content of another template. The imported template has access to the parents variables. So it's a valid strategy to have a "partial" template that for example can render an object or a defined type. Then include the template wherever you need it:
best practice is to have a partials
folder,
and every partial template begins with an underscore "_"
all templates are partial that do not extend another
template and therefore can be included.
This way you create reusable template blocks to use all over your webpage.
(Since Nimja 0.9.0) If you import other templates, make sure to use the baseDir
param with
tmpls
, tmplf
, compileTemplateString
and compileTemplateFile
.
(Since Nimja 0.10.0) You can also use the template fragment feature.
partials/_user.nimja:
<div class="col-3">
<h2>{{user.name}}</h2>
<ul>
<li>Age: {{user.age}}</li>
<li>Lastname: {{user.lastname}}</li>
</ul>
</div>
partials/_users.nimja:
<div class="row">
{% for user in users: %}
{% importnimja "partials/_user.nimja" %}
{% endfor %}
</div>
a child template can extend a master template. So that placeholder blocks in the master are filled with content from the child.
Basically the rendered template chooses its "sourrounding" template.
(Since Nimja 0.9.0) If you extend other templates, make sure to use the baseDir
param with
tmpls
, tmplf
, compileTemplateString
and compileTemplateFile
.
partials/_master.nimja
<html>
<body>
A lot of boilerplate
{% block content %}{% endblock %}
<hr>
{% block footer %}{% endblock %}
</body>
</html>
child.nimja
{% extends "partials/_master.nimja" %}
{% block content %}I AM CONTENT{% endblock %}
{% block footer %}...The footer..{% endblock %}
if the child.nimja is compiled then rendered like so:
proc renderChild(): string =
compileTemplateFile("child.nimja", baseDir = getScriptDir())
echo renderChild()
output:
<html>
<body>
A lot of boilerplate
I AM CONTENT
<hr>
...The footer..
</body>
</html>
A scope
has the same semantic as a nim block.
Variables declared inside a scope are not visible
on the outside. You can use this for code hygiene.
{% scope %}
{% let httpMethod = "POST" %}
{{ httpMethod }}
{% endscope %}
{# httpMethod is not accesible any more, you can define it again. #}
{% let httpMethod = "FOO" %}
{{ httpMethod }}
You can break out of a named scope prematurely
{%- scope foo -%}
foo
{%- break foo -%}
baa
{%- endscope -%}
in this case only "foo" is printed.
self
variableJinja describes them like so, we can do the same:
You can't define multiple {% block %} tags with the same name in the same template. This limitation exists because a block tag works in "both" directions. That is, a block tag doesn't just provide a placeholder to fill - it also defines the content that fills the placeholder in the parent. If there were two similarly-named {% block %} tags in a template, that template's parent wouldn't know which one of the blocks content to use.
If you want to print a block multiple times, you can, however, use the special self variable and call the block with that name:
<title>{% block title %}{% endblock %}</title>
<h1>{{ self.title }}</h1>
{% block body %}{% endblock %}
To change the specialSelf
variable name compile with eg.:
nim c -d:specialSelf="blocks." file.nim
Procedures can be defined like so:
{% proc foo(): string = %}
baa
{% endproc %}
{{ foo() }}
{% proc input(name: string, value="", ttype="text"): string = %}
<input type="{{ ttype }}" value="{{ value }}" name="{{ name }}">
{% endproc %}
{{ input("name", "value", ttype="text") }}
Func's have the same semantic as nim funcs, they are not allowed to have a side effect.
{% func foo(): string = %}
baa
{% endfunc %}
{{ foo() }}
macro
is an alias for proc
{% macro textarea(name, value="", rows=10, cols=40): string = %}
<textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols
}}">{{ value }}</textarea>
{% endmacro %}
{{ textarea("name", "value") }}
for {{func}}
{{proc}}
and {{macro}}
either the {{end}}
tag or
the {{endfunc}}
{{endproc}}
{{endmacro}}
are valid closing tags.
Importing works like any other ordinary Nimja templates with ìmportnimja
.
Good practice is to define procs with the "whitespacecontrol":
myMacros.nimja
{%- proc foo(): string = %}foo{% end -%}
{%- proc baa(): string = %}baa{% end -%}
myTemplate.nimja
{% importnimja "myMacros.nimja" %}
When a template extends
another template, importnimja
statements must be
in a block
they cannot stand on their own.
It might be a good idea to import these "library templates" in
the extended template (eg.: master.nimja).
Expanded template bodies can also be created as an iterator,
therefore the generated strings are not concatenated to the result
result &= "my string"
but are yielded.
This could be used for streaming templates, or to save memory when a big template is rendered and the http server can send data in chunks:
iterator yourIter(yourParams: bool): string =
compileTemplateString("{%for idx in 0 .. 100%}{{idx}}{%endfor%}", iter = true)
for elem in yourIter(true):
echo elem
###############
{% if true %}
<li> {{foo}} </li>
{% endif %}
###############
is expanded to:
###############
<li> FOO </li>
###############
the nimja template control statements leave their newline and whitespace when rendered. To fix this you can annotate them with "-":
###############
{% if true -%}
<li> {{-foo-}} </li>
{%- endif %}
###############
###############
<li>FOO</li>
###############
(Since Nimja 0.10.0)
All the render procs (tmpls
, tmplf
, compileTemplateString
and compileTemplateFile
).
Have a parameter blockToRender
.
proc render(): string =
compileTemplateStr("not rendered{% block foo %}foo{% endblock %}",
blockToRender = "foo", baseDir = getScriptDir())
tmpls("not rendered{% block foo %}foo{% endblock %}", blockToRender = "foo", baseDir = getScriptDir())
proc render(): string =
compileTemplateFile("template.nimja",
blockToRender = "foo", baseDir = getScriptDir())
tmplf("template.nimja", blockToRender = "foo", baseDir = getScriptDir())
If set only this block of a larger template is rendered.
Imagine this example where we use htmx:
page.nimja
<html>
<header>
<script src="https://unpkg.com/htmx.org@2.0.2"></script>
</header>
<body>
{% block content %}
<h1>Hello</h1>
{% block button %}
<div id="buttons">
<button hx-post="/clicked/up" hx-target="#buttons" hx-swap="outerHTML" {% if button == 10%}disabled{% endif %} >
UP Click Me {{button}}
</button>
{%- if button == 10%}you klicked enough!!{% endif -%}
</div>
{% endblock %}
{% endblock %}
</body>
</html>
When you render the whole page, everything is rendered. Good for the first visit of the site.
tmplf("page.nimja", baseDir = getScriptDir())
When you later want to update the button with htmx, you need only the "block button"
tmplf("page.nimja", blockToRender = "button" baseDir = getScriptDir())
then only this part is rendered:
{% block button %}
<div id="buttons">
<button hx-post="/clicked/up" hx-target="#buttons" hx-swap="outerHTML" {% if button == 10%}disabled{% endif %} >
UP Click Me {{button}}
</button>
{%- if button == 10%}you klicked enough!!{% endif -%}
</div>
{% endblock %}
You can also use this to get rid of some of your partials templates. For example, with this you can combine partials and extended templates:
user.nimja
{% extends partials/_base.nimja %}
{% block content %}
Information about the user.
{% block user %}
<div id="user">
{{user.firstName}}
{{user.lastName}}
</div>
{% endblock %}
also visit <a href="https://github.com/enthus1ast/nimja/blob/master/users/">other user</a>!
{% endblock %}
So a "users detail page" would render the whole thing.
tmplf("user.nimja", baseDir = getScriptDir())
But if you want to display a user somewhere else, you can just render the user
block:
userlist.nimja
<ul>
{% for user in db.getUsers %}
<li>
{% importnimja "user.nimja" "user" %}
</li>
{% endfor %}
</ul>
The optional nimjautils
module, implements some convenient procedures.
import nimja/nimjautils
Mainly:
yields a Loop
object with every item.
Inside the loop body you have access to the following fields.
Unlike jinja2 or twig where the loop variable is implicitly bound and available, we must use the loop()
iterator explicity.
{% for (loop, row) in rows.loop() %}
{{ loop.index0 }} {# which elemen (start from 0) #}
{{ loop.index }} {# which element (start from 1) #}
{{ loop.revindex0 }} {# which element, counted from the end (last one is 0) #}
{{ loop.revindex }} {# which element, counted from the end (last one is 1) #}
{{ loop.length }} {# the length of the seq, (same as mySeq.len()) #}
{% if loop.first %}The first item{% endif %} {# if this is the first loop iteration #}
{% if loop.last %}The last item{% endif %} {# if this is the last loop iteration #}
{% if loop.previtem.isSome() %}{{ loop.previtem.get() }}{% endif %} {# get the item from the last loop iteration #}
{% if loop.nextitem.isSome() %}{{ loop.nextitem.get() }}{% endif %} {# get the item from the next loop iteration #}
<li class="{{ loop.cycle(@["odd", "even"]) }}">{{row}}</li>
{% endfor %}
however, the element you iterate over must match the Concept https://github.com/enthus1ast/nimja/issues/23
This means you can propably not use Loopable
.loop()
with an iterator, since they do not have a len()
and []
within a loop you can cycle through elements:
{% for (loop, row) in rows.loop() %}
<li class="{{ loop.cycle(@["odd", "even"]) }}">{{ row }}</li>
{% endfor %}
Converts all operands into strings and concatenates them.
like: $aa & $bb
{{ "Hello " ~ name ~ "!" }}
would return (assuming name is set to 'Nim') Hello Nim!.
Includes the content of a file literally without any parsing Good for documentation etc..
proc test(): string =
let path = ("tests/basic" / "includeRawT.txt", baseDir = getScriptDir())
compileTemplateStr("""pre{{ includeRaw(path) }}suf""")
to include raw strings, or nimja code itself to a template (for documentation purpose),
you could use this construct {{"raw code"}}
proc foo(): string =
compileTemplateStr("""
foo {{"{%if true%}baa{%endif%}"}}
""")
this would then be rendered like so:
foo {%if true%}baa{%endif%}
Includes the content of a file literally without any parsing, on compiletime. This means it is included into the executable.
Includes the content of a file on compile time, it is converted to a data url. Eg:
<img src="https://github.com/enthus1ast/nimja/raw/master/{{includeStaticAsDataurl(getScriptDir() / "logo.jpg")}}">
is transformed to:
<img src="https://github.com/enthus1ast/nimja/raw/master/data:image/jpeg;charset=utf-8;base64,/9j/4AAQSkZJRg..."/>
truncates a string to "num" characters.
when the string was truncated it appends the suf
to the text.
if preserveWords
is true it will not cut words in half but
the output string could be shorter than num
characters.
proc truncate*(str: string, num: Natural, preserveWords = true, suf = "..."): string
let lorem = "Lorem ipsum, dolor sit amet consectetur adipisicing elit. Rem voluptates odio tempore voluptas beatae eum consequatur laudantium totam. Delectus fuga eveniet ab cum nulla aperiam iste ducimus odio fugit voluptas."
proc test(lorem: string): string =
compileTemplateStr("{{lorem.truncate(65)}}")
assert test(lorem) == "Lorem ipsum, dolor sit amet consectetur adipisicing elit. Rem..."
Converts newline to <br>
.
If keepNL == true, the one \n
is replaced by <br>\n
thus keeping the newlines.
func nl2br*(str: string, keepNl = true): string =
assert "foo\nbaa".nl2br == "foo<br>\nbaa"
Removes unneeded whitespaces between html tags,
warning, this is NOT smart. So it will destroy <textarea>
and <pre>
content!
check "<foo>\n\nbaa </foo>".spaceless == "<foo> baa </foo>"
check "<foo tag='tag tag'>\n\nbaa </foo>".spaceless == "<foo tag='tag tag'> baa </foo>"
check "<foo>baa baz</foo>".spaceless == "<foo>baa baz</foo>"
converts any string to an url friendly one. Removes any special chars and replaces non ASCII runes to their ASCII representation.
slugify("Lession learned german umlauts: öüä")
will output:
lession-learned-german-umlauts-oua
let allowedCharsInSlug = Letters + Digits
proc slugify*(str: string, sperator = "-", allowedChars = allowedCharsInSlug): string =
?
a shorthand for a condition, this could be used for example to toggle html classes:
proc foo(isDisabled: bool): string =
compileTemplateStr("""{% ?isDisabled: "disabled" %}""")
check "disabled" == foo(true)
check "" == foo(false)
|
a | b
is an alias to a.b
this is often used in other template engines.
proc foo(): string =
compileTemplateStr("""{{"foo baa baz" | slugify}}""")
check foo() == "foo-baa-baz"
if you need more utils in nimjautils, please PR! they should all be quite easy to implement, so they make up a good first issue/pull request!
a good inspiration WHAT to hack is jinja and twig filters.
This is a COMPILED template engine. This means you must recompile your application for every change you do in the templates!
Automatic recompilation / hot code reloading / dynamic execution is a planned feature. see the
Automatic Recompilation / Hot Code Reloading (hcr)
section
nim c -r yourfile.nim
sometimes, nim does not catch changes to template files. Then compile with "-f" (force)
nim c -f -r yourfile.nim
(Still an experimental feature, help wanted.) Automatic Recompilation enables you to change your templates and without recompiling your application, see the changes lives.
How it works:
Nimja compiles your templates (and template render functions) to a shared library (.so/.dll/.dynlib), then your host application loads this library, then on source code change, the shared library is unloaded from your host, recompiled, and loaded again.
This is normally way faster, than recompiling your whole application.
For this to work, Nimja now contains a small file watcher, you must utilize this tool in your own application.
You also must restructure you application a little bit, all you render functions must be in a separate file, this file is then compiled to a shared lib and loaded by your host.
When you go live later, you can just disable the recompilation, and compile the shared library for release, it should be very fast as well.
Below is a minimal example, a more complete example is in the example folder
Minimal example:
host.nim
# this is the file that eg. implements your webserver and loads
# the templates as a shared lib.
import nimja/hcrutils # Nimja's hot code reloading utilities
import jester, os
# We watch the templates folder for change (and also tmpls.nim implicitly)
var cw = newChangeWatcher(@[getAppDir() / "templates/"])
asyncCheck cw.recompile() # if a change is detected we recompile tmpls.nim
type
# You must declare the proc definition from your tmpls.nim here as well.
ProcNoParam = proc (): string {.gcsafe, stdcall.}
ProcId = proc (id: string): string {.gcsafe, stdcall.}
routes:
get "/":
resp dyn(ProcNoParam, "index")
get "/id/@id":
resp dyn(ProcId, "detail", @"id")
tmpls.nim
# this file contains you render functions
# is compiled to a shared lib and loaded by your host application
# to keep compilation fast, use this file only for templates.
# this file is also watched by the filewatcher.
# It can also be changed dynamically!
import nimja
import os # for `/`
proc index*(): string {.exportc, dynlib.} =
var foos = 1351 # change me i'm dynamic :)
compileTemplateFile("templates/index.nimja", baseDir = getScriptDir())
proc detail*(id: string): string {.exportc, dynlib.} =
compileTemplateFile("templates/detail.nimja", baseDir = getScriptDir())
templates/
templates/partials/_master.nimja
<head>
<title>Hello, world!</title>
</head>
<body>
<h1><a href="https://github.com/enthus1ast/nimja/blob/master/">Nimja dynamic test</a></h1>
<div>
{% block content %}{% endblock %}
</div>
</body>
</html>
templates/index.nimja
{% extends "templates/partials/_master.nimja" %}
{% block content %}
<h1>Hello, world! {{foos}}</h1>
index
{% for idx in 0..100 %}
<a href="https://github.com/enthus1ast/nimja/blob/master/id/{{idx}}">{{idx}}</a>
{%- endfor %}
{% endblock %}
templates/detail.nimja
{% extends "templates/partials/_master.nimja" %}
{% block content %}
detail
<a href="https://github.com/enthus1ast/nimja/blob/master/id/{{id}}">{{id}}</a>
{% endblock %}
you can now change any of the templates or the tmpls.nim
files.
Later if you wanna go live, comment out the
asyncCheck cw.recompile() # if a change is detected we recompile tmpls.nim
line.
If you are using VSCode to develop your nim app, you can still associate nimja template files for color syntax and formating with vscode as an html file. Add this segment to your settings.json in vscode:
"files.associations": {
"*.nwt": "html", // Nimja deprecated templates
"*.nimja": "html", // Nimja new templates
},
nim c -d:dumpNwtAst -r yourfile.nim # <-- dump NwtAst
nim c -d:dumpNwtAstPretty -r yourfile.nim # <-- dump NwtAst as pretty json
nim c -d:nwtCacheOff -r yourfile.nim # <-- disables the NwtNode cache
nim c -d:noPreallocatedString -r yourfile # <-- do not preallocate the output string
nim c -d:noCondenseStrings -r yourfile.nim # <-- disables string condense see #12
nim c -d:dumpNwtMacro -r yourfile.nim # <-- dump generated Nim macros
importnimja
tmpls
, tmplf
, compileTemplateString
and compileTemplateFile
) got a "blockToRender" parameter, when set, only the given block is rendered.tmpls
, tmplf
, compileTemplateString
and compileTemplateFile
) got a baseDir
param:
compileTemplateStr("""{{importnimja "some/template.nimja"}}""", baseDir = getScriptDir())
tmpls("""{{importnimja "some/template.nimja"}}""", baseDir = getScriptDir())
compileTemplateFile("some/template.nimja", baseDir = getScriptDir())
tmpls("some/template.nimja", baseDir = getScriptDir())
The use of tmplf(getScriptDir() / "foo.nimja")
is discourage, use tmplf("foo.nimja", baseDir = getScriptDir())
instead.
The old way could still work in some cirumstances though.
But its neccesary if you plan to import your nimja template code into other code.
NImport
.when
blocks./
scope
and endscope
break
and continue
for the for loopcase
of
and endcase
compileTemplateStr
and compileTemplateFile
tmpls
and tmplf
when
compile time ifimportnimja
deprecated importnwt
(importnwt is still valid for now)result
is string.{{endfunc}}
{{endproc}}
{{endmacro}}
for consistency.tmpls
and tmplf
procs to use inline.includeRawStatic
and includeStaticAsDataurl