Caveman is a 1kb JS templating engine, written for long-running single-page applications that render tens of thousands of DOM elements at a time.
Caveman's markup language is built using an extensible macro system, which allows for arbitrary script execution, explicit logic, and partials. The library is lightweight (1kb compressed), has no dependencies, adds a single Caveman
variable to the global namespace, and seems from initial benchmark tests to be very fast, nearly as fast as native JS concatenation.
Installation
npm install caveman
bower install caveman
Usage Examples
1. Client-side Compilation & Rendering
This is an easy setup, but it's not as fast as precompiling your templates on the server (see below). This example assumes jQuery already exists on the page.
2. Server-side Compilation, Client-side Rendering
Assuming a node application with templates in app/views/templates/*.html
and generated assets in public/bundled
.
-
Using Grunt and grunt-caveman, configure your Caveman task:
grunt;grunt; -
Run Grunt to generate your
templates.js
file. Partials will be named according to their file names, without the ".html" extension. -
You should now have a Caveman template registry ready to go on the client-side:
3. Server-side Compilation and Rendering
You can also use Caveman for static site generation. Let's assume you have your caveman templates in ./templates
and generated assets in ./public
. Using Grunt and grunt-caveman, configure your Caveman task like so:
grunt; grunt;
Concepts
Escaping
Caveman does not escape input by default, but you can enable that by setting Caveman.options.escapeByDefault = true
. If you want to escape an individual string, you can do that with the escape
macro:
{{- escape d.html }}
Scope
Caveman doesn't use with
blocks or do any scope lookup under the hood. Data is passed in to a Caveman template as the argument d
, so instead of {{foo}}
you use {{d.foo}}
. Within for
and each
blocks, the scope of d
becomes block-level, as illustrated here:
{{- for d.posts as post }} {{post.title}} {{- for post.images }} <!-- d is now block level. --> {{- end }} <!-- Scope of d is restored. --> {{- for post.images as image }} <!-- The scope of d is unaffected since we're using `for as`. --> <!-- We can still reference anything further up the scope chain: --> {{d.posts[0].images[0].src}} {{- end }} {{- each post.images[0] }} <!-- d is now block-level. --> {{_key}}: {{d}} {{- end }} {{- each post.images[0] as attr }} <!-- The scope of d is unaffected since we're using `each as`. --> {{_key}}: {{attr}} <!-- We can still reference anything further up the scope chain: --> {{d.posts[0].images[0].src}} {{- end }} {{- end }}
Custom Macros
Macros can be added or modified quite easily, even after templates are compiled. For example, a "tableClass" macro that adds zebra stripes and "first" and "last" classes, depending on where it is in the array:
Caveman; data = rows: text: 'a' text: 'b' text: 'c'
<!-- template --> {{- for d.rows as row }} {{_i}}: {{row.text}} {{- end }} <!-- rendered HTML --> 0: a 1: b 2: c
Arbitrary Script Execution
;
<!-- template -->{{- for d.rows }} {{d}} x {{d}} = {{- print d * d }}{{- end }} <!-- rendered HTML -->1 x 1 = 12 x 2 = 43 x 3 = 9
Interpolation Behavior
<!-- exampleTemplate.html -->string: {{d.strings}}empty string: {{d.emptyString}}boolean false: {{d.booleanFalse}}boolean true: {{d.booleanTrue}}null: {{d.nullValue}}undefined: {{d.undefinedValue}}floats: {{d.floats}}integers: {{d.ints}}zero: {{d.zero}}arrays (bracket notation): {{d.arrays[2]}}arrays of objects (dot and bracket notation): {{d.arraysOfObjects[1].b}}
Caveman;
<!-- rendered HTML -->string: 123empty string:boolean false: falseboolean true: truenull:undefined:floats: 123.12integers: 1234zero: 0arrays (bracket notation): 3arrays of objects (dot and bracket notation): 2
Macro Documentation
{{- if expression }}
{{- unless expression }}
{{- else }}
{{- else if expression }}
{{- end }}
{{- for d.posts as post }} {{- unless post.hidden }} {{post.title}} {{- if post.comments.length > 0 }} {{- for post.comments as comment }} {{comment.text}} {{- end }} {{- else }} No comments! {{- end }} {{- end }} {{- end }}
The if
, unless
, and end
macros have shortcuts, respectively:
{{? expression }}
{{^ expression }}
{{/}}
{{- for array }}
{{- for array as obj }}
The for
macro iterates through arrays. These variables are available in the block scope:
_i
= the current index of the for loop, starting with zero_len
= the length of the for loop.
var data = users: name: 'Jimmy' email: 'jimmy@gmail.com' name: 'Ralph' email: 'ralph@gmail.com' ;;
<!-- template --> {{- for d.users as user }} Name {{user.name}} Email {{user.email}} {{- end }} <!-- rendered HTML --> Name Jimmy Email jimmy@gmail.com Name Ralph Email ralph@gmail.com
{{- each obj }}
{{- each obj as attr }}
each
is meant for iterating through object properties, using a closure instead of a for loop. The _key
variable is available in the block scope.
data = cars: make: 'Volvo' model: '245s' year: 1976 make: 'Saab' model: '900s' year: 1985 ;
<!-- template -->{{- for d.cars as car }} {{- each car as attribute }} {{_key}}: {{attribute}} {{- end }} {{- end }} <!-- rendered HTML --> make: Volvo model: 245s year: 1976 make: Saab model: 900s year: 1984
{{- with a.b.c.obj }}
{{- with a.b.c.obj as obj }}
with
allows you to scope an object to d
(or to a named variable using with foo as bar
) within a block.
<!-- template -->{{- for d.posts as post }} {{- with post.author as author }} {{author.name}} {{- end }}{{- end }}
{{- print expression }}
print
writes the expression's returned value. The _i
character is the current index of the array. d
is the current value, which happens to be a string.
<!-- template -->{{- for d.rows }} {{d}} x {{d}} = {{- print d * d }}{{- end }} <!-- rendered HTML -->1 x 1 = 12 x 2 = 43 x 3 = 9
{{- log expression }}
Writes {expression} to console.log.
- log xyz
{{- render partialName }}
{{- render partialName context }}
Renders partial {name} using optional {scope}.
Compiled templates should be registered using the Caveman.register
method so they can be used as partials.
CavemanCaveman var data = emails: email: 'jimmy@gmail.com' name: 'Jimmy' email: 'ralph@gmail.com' name: 'Ralph' className: 'active' email: 'joe@gmail.com' name: 'Joe' ;Caveman;
<!-- "emailList" template -->{{- for d.emails }} {{- render emailLink }}{{- end }} <!-- "emailLink" template -->{{d.name}} <!-- rendered HTML --> Jimmy Ralph Joe
{{// comment }}
Allows comments in a template without being included in the rendered output.
var template = 'Foo {{// This is a comment. }} bar'; Caveman;Caveman;
Foo bar
{{- escape expression }}
Prevent HTML/JS from being evaluated. You can enable this behavior globally by setting Caveman.options.escapeByDefault = true
.
var data = html: '<script>alert("HELLO!");</script> & \'';var template = '{{- escape d.html }}'; Caveman;Caveman;
<script>alert("HELLO!");</script> & '
{{- unescape expression }}
Allow HTML/JS to be evaluated, even if Caveman.options.escapeByDefault
was already set to true
.
var data = html: '<script>alert("HELLO!");</script> & \'';var template = '{{- unescape d.html }}'; Caveman;Caveman;
& '
Method Reference
Caveman
Returns either a compiled template function, or the rendered HTML if data is passed in. The latter approach should not be used in production as the compiled template is not cached.
// returns compiled template function // returns rendered HTML
Caveman.compile(template)
Returns a compiled template string. If you're sending pre-compiled templates to the client, you should use this method, otherwise you don't really need to use this. If you're compiling templates on the client-side, you should just use Caveman.register
and Caveman.render
.
var template = '{{- for d.users as user }}<span>{{user.name}}</span>{{- end }}'var compiled = Caveman; Caveman;
Caveman.register(templateName, uncompiledTemplateString)
Caveman.register(templateName, compiledTemplateFunction)
Register a partial {name} using template {template}, allowing it to be used later on with Caveman.render
. Accepts both compiled and uncompiled templates.
var template = '{{- for d.users as user }}<span>{{user.name}}</span>{{- end }}'Caveman;
Caveman.render(templateName, data)
Render a compiled template {name} using {data}.
var data = users: name: 'Mario' name: 'Luigi' Caveman;// > "<span>Mario</span><span>Luigi</span>"
Caveman.addMacro(macroName, macroDefinition)
Adds or updates a macro {macroName} with macro {macro}. Macros are objects with the following keys:
- find: Required. The regex to test the str against.
- replace: Required. A string or function that returns a replacement expression.
- blockEnd: Optional. If this is a block, what should be added during the matching {{- end }} macro.
- prefix: Optional. If anything needs to be added at the beginning of the compiled template.
- shortcut: Optional. Define a shortcut syntax for this macro.
All existing macros are defined using this method, for example:
Caveman; Caveman;
Options
To use custom tags (e.g. ERB-style tags), override these two options before compiling your templates:
CavemanoptionsopenTag = '<%'; // defaults to '{{'CavemanoptionscloseTag = '%>'; // defaults to '}}'
Remove indentation by shrink wrapping your templates:
CavemanoptionsshrinkWrap = true; // defaults to false
Automatically escape all input:
CavemanoptionsescapeByDefault = true; // defaults to false
Benchmarks
If you only look at pure rendering performance, Caveman shows a dramatic performance gain over Hogan, Handlebars and Lodash:
However a more real-world test that includes DOM manipulation shows a more modest improvement:
YMMV.
Running the test suite
npm test
License
MIT. Copyright © 2016 Andrew Childs