joshbuddy / emjay

Kickass Javascript templating for node.js and others.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Emjay

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.

Delimiters

In Emjay, there are three types of delimiters.

Direct output

  • [= -] - 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.

Example

[- // Outputting a variable passed into the template. -]
[=title-]

This would render the title variable directly into the page. It would be escaped.

Preprocessor block

  • [% %] - 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.

Example

[- // 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.

Running code

  • [- -] - 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.

Example

[- // Outputting a variable passed into the template. -]
[- this.append('<testing>') -]

This would add &lt;testing&gt; into the page.

String tainting

All strings can be made safe by calling makeSafe() on them. This returns a SafeString object, which will not get escaped.

Example

[- // 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-]

Node.js

A more thorough node.js based example in available in the examples directory.

API

About

Kickass Javascript templating for node.js and others.


Languages

Language:JavaScript 100.0%