Nolate - NO LAme TEmplate system

OVERVIEW


Nolate is a template system similar to erb that is designed for not consuming some huge amount of CPU without a good reason. It is written in pure Ruby. Nolate is distributed under a two clause BSD license for max freedom.

Templates can include code inside <%= %> that is evaluated with eval() and substituted to the string.

Also occurrences of <%#something%> are substituted with the value of the hash field :something of an additional hash passed to nolate() or nlt() functions.

IS IT SUPER FAST?


Fast enough that a small template substitution is not measurable by the apache benchmark against a sample Sinatra application. Surprisingly this is not as common as it should be.

HOW TO USE IT?


Nolate consists of just a few functions. The first is nolate() that is the core of the template system:

nolate("The sum is <%= 2+2 %> Also substitute <%#myfield%> ok",
       {:myfield => 10})

The array is optional, if you don’t have <%#%> style substitutions you can simply omit it.

The second function is nlt(), and is used to also handle loading the template from a ‘views’ directory. The above example can be translated using nlt() just creating a file ‘views/index.nlt’ with the following content:

The sum is <%= 2+2 %> Also substitute <%#myfield%> ok

Then we can use nlt() calling:

nlt("index.nlt", {:myfield => "something"})

the nlt() funciton will take care to cache templates into memory. In order to flush this templates to force reloading just call the third and final provided function:

nlt_flush_templates()

It is possible to pass the template name as a symbol like in:

nlt(:index)

nlt will add “.nlt” at the end of the name when it is a symbol.

SUPPORTED SUBSTITUTIONS


<%= somecode %> Evaluates somecode and substitutes the return value. <% somecode %> Evaluates somecode. <%#filed_name%> Substituted the value of the specified filed of the hash

passed to nolate() or nlt() as optional argument.

It is possible to interleave template and Ruby code together like in the following example:

<% (0..5).each{|x| %> <li><%=x%></li> <% } %>

USING LAYOUTS


Nolate suppots the concept of layout. You can specify to use a layout using the following call:

nlt_set_layout(:layout)

The above call specifies to use “views/layout.nlt” as template.

The layout is a normal nolate template that contains somewhere a substitution in the form of: <%#content%>. When a layout is set what happens is that all the calls to nolate() or nlt() are processed, then the result is substituted to the layout template.

The layout template can also include any other standard nolate substitution and code evaluation.

It is possible to change layout at runtime, or to disable the layout setting it to nil.

CONTRIBUTE


Please send me pull requests: github.com/antirez/nolate

So far thank you to:

@soveran
@brmichel
@JEG2
Emmanuel Oga (https://github.com/EmmanuelOga)
@czarneckid

It is not too late… Salvatore