Let’s talk a bit about templating in the JavaScript world. Right now no good standard exists. Many of the templating systems people have creating assume that the templating engine can directly return the computed value. Mustache.js, though admirable, uses {{
and }}
for its delimiters, a character sequence which can naturally occur in JavaScript.
I’ve set out to solve the problem of asynchronous requirements, making those easy to deal with and natural, easy-to-type delimiters.
In Emjay, there are three types of delimiters.
-
[= -]
- This is for simple outputting. Values can be computed and outputted, or variables bound at run-time can be accessed. This method performs HTML escaping.
[- // Outputting a variable passed into the template. -] [=title-]
This would render the title
variable directly into the page. It would be escaped.
-
[% %]
- This is for asynchronous interaction. A special variable,__runtime
is available within this block.__runtime
has the following methods (this
will also be__runtime
):-
write
- This allows you to write raw content to the template which will later be eval’ed. It returns the__runtime
object. -
append
- This allows you to output a string. It returns the__runtime
object. -
done
- This allows you to mark your block as done and continue compilation of the template. Nothing should be done after calling this method.
-
As well, the bindings passing into the template are available as this.base.bindings
.
[- // read a file, and output it. -] [% Posix.cat('myfile.txt', function(contents) { __runtime.append(contents).done() }) %]
This would load myfile.txt, and output it entire contents in place.
-
[- -]
- This allows you to write JavaScript code that will be evaluated, but not output.
You can still output if you really want to though as seen in the example.
[- // Outputting a variable passed into the template. -] [- this.append('<testing>') -]
This would add <testing>
into the page.
All strings can be made safe by calling makeSafe()
on them. This returns a SafeString object, which will not get escaped.
[- // Outputting a variable passed into the template. -] [=title.makeSafe()-]
This would perform no escaping on the title
variable. Alternately, you can use the [== -]
syntax to output.
[- // Outputting a variable passed into the template. -] [==title-]
A more thorough node.js based example in available in the examples directory.