Use nimja without wrapping code in a proc for `result` variable
ajusa opened this issue · 5 comments
One thing I've noticed about Nimja is that it assumes there is a result
variable defined that is of a string type. It'd be nice if I could use this in places without needing to define a wrapper proc, eg inline with a Jester route definition. In that case, the variable result
is already declared by the framework.
I'd like to be able to do
resp compileTemplateStr("some nimja code {{someParam}}")
or
var a = compileTemplateStr("some nimja code {{someParam}}")
in any arbitrary block of code without it relying on a result
variable. I think it is possible to add this without any breaking changes, but if it isn't then I believe you'd need some sort of overload.
yes good point.
What do you think about this? Could add this to Nimja.
If you have a good name for these functions, please share :)
import nimja
proc tmpls*(str: static string): string {.inline.} =
## compiles a Nimja template string and returns directly.
compileTemplateStr(str)
proc tmplf*(path: static string): string {.inline.} =
## compiles a Nimja template file and returns directly
compileTemplateFile(path)
when isMainModule:
var baa = 1337
echo tmpls("foo {{baa}}")
Sorry for the late response - this doesn't quite work in Jester due to scoping issues. Eg, if I declare a variable that isn't global the tmpls
proc can't see it for interpolation. I have code that looks like this
var post = postById(@"id")
resp tmpls """
<textarea placeholder="Write here" name="text">{{post.text}}</textarea>
<button hx-get="/posts/{{post.id}}">Cancel</button>
<button hx-put="/posts/{{post.id}}">Update</button>"""
which doesn't work as it is being ran within a Jester route, and post
isn't a global variable.
I'll have a look again, thanks for reporting.
@ajusa please have a look if this works for you know.
in my tests this works now:
import jester
settings:
port = 8989.Port
routes:
get "/hello/@name":
var nimjaTmplsVar = 1.3 # only here to show we do not shadow this
resp tmpls"""<h1>{{@"name"}}</h1>"""
Yes, thank you so much for fixing it!