├── .gitignore ├── .travis.yml ├── index.js ├── lib └── filesystem.js ├── package.json ├── readme.md └── test ├── ejs-fixtures ├── backslash.ejs ├── backslash.html ├── double-quote.ejs ├── double-quote.html ├── error.ejs ├── error.out ├── include.css.ejs ├── include.css.html ├── include.ejs ├── include.html ├── includes │ ├── menu-item.ejs │ └── menu │ │ └── item.ejs ├── menu.ejs ├── menu.html ├── messed.ejs ├── messed.html ├── newlines.ejs ├── newlines.html ├── no.newlines.ejs ├── no.newlines.html ├── para.ejs ├── pet.ejs ├── single-quote.ejs ├── single-quote.html ├── style.css └── user.ejs ├── ejs.js ├── fixtures ├── countries.qejs ├── inherit-A.qejs ├── inherit-B.qejs ├── inherit-C.qejs └── long.qejs └── index.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 0.6 4 | - 0.8 5 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 2 | /*! 3 | * EJS 4 | * Copyright(c) 2012 TJ Holowaychuk 5 | * MIT Licensed 6 | */ 7 | 8 | var resolverRead = require('./lib/filesystem.js').resolverRead; 9 | 10 | /** 11 | * Module dependencies. 12 | */ 13 | var Q = require('q'); 14 | 15 | function all(promises) { 16 | return Q.when(promises, function (promises) { 17 | var countDown = promises.length; 18 | if (countDown === 0) { 19 | return Q.resolve(promises); 20 | } 21 | var deferred = Q.defer(); 22 | promises.forEach(function (promise, index) { 23 | if (Q.isFulfilled(promise)) { 24 | promises[index] = Q.nearer(promise); 25 | if (--countDown === 0) { 26 | deferred.resolve(promises); 27 | } 28 | } else { 29 | Q.when(promise, function (value) { 30 | promises[index] = value; 31 | if (--countDown === 0) { 32 | deferred.resolve(promises); 33 | } 34 | }) 35 | .fail(deferred.reject); 36 | } 37 | }); 38 | return deferred.promise; 39 | }); 40 | } 41 | 42 | /** 43 | * Escape the given string of `html`. 44 | * 45 | * @param {String} html 46 | * @return {String} 47 | * @api public 48 | */ 49 | exports.escape = function escape(html){ 50 | return when(html, function (html) { 51 | return String(html) 52 | .replace(/&(?!\w+;)/g, '&') 53 | .replace(//g, '>') 55 | .replace(/"/g, '"'); 56 | }); 57 | }; 58 | 59 | 60 | 61 | /** 62 | * Library version. 63 | */ 64 | 65 | exports.version = '0.7.2'; 66 | 67 | 68 | /** 69 | * Intermediate js cache. 70 | * 71 | * @type Object 72 | */ 73 | 74 | var cache = {}; 75 | 76 | /** 77 | * Clear intermediate js cache. 78 | * 79 | * @api public 80 | */ 81 | 82 | exports.clearCache = function(){ 83 | cache = {}; 84 | }; 85 | 86 | 87 | /** 88 | * Re-throw the given `err` in context to the 89 | * `str` of qejs, `filename`, and `lineno`. 90 | * 91 | * @param {Error} err 92 | * @param {String} str 93 | * @param {String} filename 94 | * @param {String} lineno 95 | * @api private 96 | */ 97 | 98 | function rethrow(err, str, filename, lineno){ 99 | var lines = str.split('\n') 100 | , start = Math.max(lineno - 3, 0) 101 | , end = Math.min(lines.length, lineno + 3); 102 | 103 | // Error context 104 | var context = lines.slice(start, end).map(function(line, i){ 105 | var curr = i + start + 1; 106 | return (curr == lineno ? ' >> ' : ' ') 107 | + curr 108 | + '| ' 109 | + line; 110 | }).join('\n'); 111 | 112 | // Alter exception message 113 | err.path = filename; 114 | err.message = (filename || 'ejs') + ':' 115 | + lineno + '\n' 116 | + context + '\n\n' 117 | + err.message; 118 | 119 | throw err; 120 | } 121 | 122 | /** 123 | * Parse the given `str` of qejs, returning the function body. 124 | * 125 | * @param {String} str 126 | * @return {String} 127 | * @api public 128 | */ 129 | 130 | var parse = exports.parse = function(str, options){ 131 | var options = options || {} 132 | , open = options.open || exports.open || '<%' 133 | , close = options.close || exports.close || '%>'; 134 | 135 | var buf = [ 136 | "var buf = [];" 137 | , "\nwith (locals) {" 138 | , "\n buf.push('" 139 | ]; 140 | 141 | var lineno = 1; 142 | 143 | var consumeEOL = false; 144 | for (var i = 0, len = str.length; i < len; ++i) { 145 | if (str.slice(i, open.length + i) == open) { 146 | i += open.length 147 | 148 | var prefix, postfix, line = '__stack.lineno=' + lineno; 149 | switch (str.substr(i, 1)) { 150 | case '=': 151 | prefix = "', escape((" + line + ', '; 152 | postfix = ")), '"; 153 | ++i; 154 | break; 155 | case '-': 156 | prefix = "', (" + line + ', '; 157 | postfix = "), '"; 158 | ++i; 159 | break; 160 | default: 161 | prefix = "');" + line + ';'; 162 | postfix = "; buf.push('"; 163 | } 164 | 165 | var end = str.indexOf(close, i) 166 | , js = str.substring(i, end) 167 | , start = i 168 | , n = 0; 169 | 170 | if ('-' == js[js.length-1]){ 171 | js = js.substring(0, js.length - 1); 172 | consumeEOL = true; 173 | } 174 | function searchAndSplit(js, splitter){ 175 | var output = [[]]; 176 | var ignoreNext = false; 177 | var inSingleQuotes = false; 178 | var inDoubleQuotes = false; 179 | var inComment = false; 180 | function push(c){ 181 | output[output.length-1].push(c); 182 | } 183 | for(var x = 0; x 1){ 234 | return output.map(function(part){ 235 | return part.join(''); 236 | }); 237 | } else { 238 | return false; 239 | } 240 | } 241 | (function(){ 242 | 243 | var split = searchAndSplit(js, '->'); 244 | if(split){ 245 | var input = split[0]; 246 | var output = split[1]; 247 | var manyIn = (/^\s*\[.*\]\s*$/g).test(input); 248 | var manyOut = (/^\s*\[.*\]\s*$/g).test(output); 249 | if(manyIn){ 250 | input = 'all(' + input + ')'; 251 | } else { 252 | input = 'Q.when(' + input + ')'; 253 | } 254 | if(manyOut){ 255 | output = (/^\s*\[(.*)\]\s*$/g).exec(output)[1]; 256 | prefix = "', (" + line + ', (function(buf){return ' + input + '.spread(function('; 257 | }else{ 258 | prefix = "', (" + line + ', (function(buf){return ' + input + '.then(function('; 259 | } 260 | js = output; 261 | postfix = '){try {'+"buf.push('"; 262 | } 263 | }()); 264 | (function(){ 265 | var split = searchAndSplit(js, '<-'); 266 | if(split){ 267 | prefix += split[0]; 268 | prefix += ";return all(buf).invoke('join','')} catch (err) { rethrow(err, __stack.input, __stack.filename, __stack.lineno); } });}([]))));" 269 | js = split[1]; 270 | } 271 | }()); 272 | 273 | while (~(n = js.indexOf("\n", n))) n++, lineno++; 274 | buf.push(prefix, js, postfix); 275 | i += end - start + close.length - 1; 276 | 277 | } else if (str.substr(i, 1) == "\\") { 278 | buf.push("\\\\"); 279 | } else if (str.substr(i, 1) == "'") { 280 | buf.push("\\'"); 281 | } else if (str.substr(i, 1) == "\r") { 282 | buf.push(" "); 283 | } else if (str.substr(i, 1) == "\n") { 284 | if (consumeEOL) { 285 | consumeEOL = false; 286 | } else { 287 | buf.push("\\n"); 288 | lineno++; 289 | } 290 | } else { 291 | buf.push(str.substr(i, 1)); 292 | } 293 | } 294 | 295 | buf.push("');\n}\nreturn all(buf).invoke('join', '');"); 296 | return buf.join(''); 297 | }; 298 | 299 | /** 300 | * Compile the given `str` of qejs into a `Function`. 301 | * 302 | * @param {String} str 303 | * @param {Object} options 304 | * @return {Function} 305 | * @api public 306 | */ 307 | 308 | var compile = exports.compile = function(str, options){ 309 | options = options || {}; 310 | 311 | var input = JSON.stringify(str) 312 | , filename = options.filename 313 | ? JSON.stringify(options.filename) 314 | : 'undefined'; 315 | 316 | // Adds the fancy stack trace meta info 317 | str = [ 318 | 'var __stack = { lineno: 1, input: ' + input + ', filename: ' + filename + ' };', 319 | rethrow.toString(), 320 | 'try {', 321 | exports.parse(str, options), 322 | '} catch (err) {', 323 | ' rethrow(err, __stack.input, __stack.filename, __stack.lineno);', 324 | '}' 325 | ].join("\n"); 326 | 327 | if (options.debug) console.log(str); 328 | 329 | try { 330 | var fn = new Function('locals, escape, Q, all', str); 331 | } catch (err) { 332 | if ('SyntaxError' == err.name) { 333 | err.message += options.filename 334 | ? ' in ' + filename 335 | : ' while compiling qejs'; 336 | err.source = str; 337 | } 338 | throw err; 339 | } 340 | return function(locals){ 341 | return fn.call(this, locals || {}, exports.escape, Q, all); 342 | } 343 | }; 344 | 345 | /** 346 | * Render the given `str` of qejs. 347 | * 348 | * Options: 349 | * 350 | * - `locals` Local variables object 351 | * - `cache` Compiled functions are cached, requires `filename` 352 | * - `filename` Used by `cache` to key caches 353 | * - `scope` Function execution context 354 | * - `debug` Output generated function body 355 | * - `open` Open tag, defaulting to "<%" 356 | * - `close` Closing tag, defaulting to "%>" 357 | * 358 | * @param {String} str 359 | * @param {Object} options 360 | * @return {>String} 361 | * @api public 362 | */ 363 | exports.render = function(str, options){ 364 | try{ 365 | var fn, options = options || {}; 366 | 367 | 368 | if (typeof options.render === 'undefined' && options.filename) { 369 | options.render = function (subpath, suboptions) { 370 | suboptions = (suboptions || {}); 371 | Object.keys(options).forEach(function (key) { 372 | if(key !== 'inherits' && key !== 'render' && typeof suboptions[key] === 'undefined') suboptions[key] = options[key]; 373 | }); 374 | return exports.renderFile(subpath, (suboptions || options), options.filename); 375 | }; 376 | } 377 | 378 | var inherits = null; 379 | if(typeof options.inherits === 'undefined' && options.filename) { 380 | options.inherits = function (path) { 381 | if(inherits !== null) throw new Error("It is an error to call inherits multiple times from one QEJS file"); 382 | inherits = path; 383 | return path; 384 | }; 385 | } 386 | 387 | if (options.cache) { 388 | if (options.filename) { 389 | fn = cache[options.filename] || (cache[options.filename] = compile(str, options)); 390 | } else { 391 | throw new Error('"cache" option requires "filename".'); 392 | } 393 | } else { 394 | fn = compile(str, options); 395 | } 396 | 397 | options.__proto__ = options.locals; 398 | 399 | var inner = fn.call(options.scope, options); 400 | if (inherits && options.filename) { 401 | var parentoptions = {}; 402 | Object.keys(options).forEach(function (key) { 403 | if(key !== 'inherits' && key !== 'render') parentoptions[key] = options[key]; 404 | }); 405 | parentoptions.contents = inner; 406 | return exports.renderFile(inherits, parentoptions, options.filename); 407 | } else { 408 | return inner; 409 | } 410 | }catch (ex){ 411 | return Q.reject(ex); 412 | } 413 | }; 414 | 415 | /** 416 | * Render an EJS file at the given `path` 417 | * 418 | * @param {String} path 419 | * @param {Object} [options] 420 | * @return {>String} 421 | * @api public 422 | */ 423 | 424 | exports.renderFile = function(path, options, source){ 425 | var key = path + ':string'; 426 | 427 | options = options || {}; 428 | 429 | try { 430 | var file = resolverRead(options.cache, path, source); 431 | options.filename = file.path; 432 | return exports.render(file.str, options); 433 | } catch (ex) { 434 | return Q.reject(ex); 435 | } 436 | }; 437 | 438 | function when(promise, callback, errback) { 439 | if (Q.isFulfilled(promise)) { 440 | return Q.resolve(callback(Q.nearer(promise))); 441 | } else { 442 | return promise.then(callback, errback); 443 | } 444 | } -------------------------------------------------------------------------------- /lib/filesystem.js: -------------------------------------------------------------------------------- 1 | var fs = require('fs'); 2 | var path = require('path'); 3 | var exists = fs.existsSync?fs.existsSync:path.existsSync; 4 | 5 | var cache = {}; 6 | 7 | module.exports.resolverRead = resolverRead; 8 | function resolverRead(cacheEnabled, to, from){ 9 | if (cacheEnabled && cache['to:' + to + 'from:' + from]) { 10 | return {str: '', path: cache['to:' + to + 'from:' + from]}; 11 | } 12 | var path = resolvePath(to, from); 13 | if (cacheEnabled) cache['to:' + to + 'from:' + from + ':resolves-to'] = path; 14 | return readFile(path); 15 | } 16 | 17 | 18 | function resolvePath(to, from){ 19 | var paths = []; 20 | var i = -1; 21 | var extnames; 22 | if(!from) return to; 23 | 24 | 25 | if (path.extname(to) === '') { 26 | extnames = ['.qejs', '.ejs', '.html']; 27 | } else { 28 | extnames = ['']; 29 | } 30 | 31 | var dirname = path.dirname(from); 32 | 33 | var root = path.dirname(require.main.filename); 34 | while (true) { 35 | i++; 36 | if(i === extnames.length){ 37 | i = 0; 38 | var old = dirname; 39 | dirname = path.join(dirname, '..'); 40 | if(old === dirname) return failedToFind(to, from, paths); 41 | } 42 | var p = path.join(dirname, to) + extnames[i]; 43 | paths.push(p); 44 | if (exists(p)) return p; 45 | } 46 | } 47 | function failedToFind(to, from, paths) { 48 | throw new Error('No file could be resolved for "' + to + '" from "' + from + '". The following paths were tried:\n' 49 | + paths.map(function (p) {return ' - "' + p + '"'}).join("\n")); 50 | } 51 | 52 | var read = fs.readFileSync; 53 | function readFile(path) { 54 | var res = {str: read(path, 'utf8'), path: path}; 55 | return res; 56 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "qejs", 3 | "description": "Asyncronous Embedded JavaScript Templates with Q", 4 | "version": "3.0.5", 5 | "keywords": [ 6 | "templating", 7 | "template", 8 | "engine", 9 | "promises", 10 | "Q", 11 | "EJS", 12 | "JavaScript", 13 | "async", 14 | "Asyncronous" 15 | ], 16 | "dependencies": { 17 | "q": "0.8.x" 18 | }, 19 | "devDependencies": { 20 | "mocha": "*", 21 | "should": "*" 22 | }, 23 | "optionalDependencies": {}, 24 | "engines": { 25 | "node": "*" 26 | }, 27 | "author": "JEPSO (http://www.jepso.com)", 28 | "homepage": "http://substance.io/forbeslindesay/qejs", 29 | "repository": { 30 | "type": "git", 31 | "url": "git://github.com/jepso/QEJS.git" 32 | }, 33 | "scripts": { 34 | "prepublish": "mocha", 35 | "test": "mocha -R spec" 36 | } 37 | } -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://secure.travis-ci.org/jepso/QEJS.png?branch=master)](http://travis-ci.org/jepso/QEJS) 2 | # Asyncronous Embedded JavaScript Templates with Q 3 | 4 | ![QEJS](http://i.imgur.com/WRIlB.png) 5 | 6 | This library impliments Embedded JavaScript with some asyncronous additions provided by Q. It is broadly based on https://github.com/visionmedia/ejs and fully supports everything except filters. For a full discussion of the reasoning behind this, see Features below. The promises implimentation for ayncronous operations uses https://github.com/kriskowal/q so you'll need to make sure that all asyncronous functions/values you supply to the templates are 'thenables' so that they'll work with Q. All that means in practice is that you need your promises to have a function `then` that you can call with a promise. 7 | 8 | ## Installation 9 | 10 | $ npm install qejs 11 | 12 | ## Example 13 | 14 | <% if (user) { %> 15 |

<%= user.getNameAsync() %>

16 | <% } %> 17 | 18 | ## Usage 19 | 20 | qejs.compile(str, options); 21 | // => Function 22 | 23 | qejs.render(str, options); 24 | // => promise 25 | 26 | qejs.render(str, options).then(function(output){ 27 | //output is a string 28 | }); 29 | 30 | ## Options 31 | 32 | - `cache` Compiled functions are cached, requires `filename` 33 | - `filename` Used by `cache` to key caches 34 | - `scope` Function execution context 35 | - `debug` Output generated function body 36 | - `open` Open tag, defaulting to "<%" 37 | - `close` Closing tag, defaulting to "%>" 38 | - * All others are template-local variables 39 | 40 | ## Custom tags 41 | 42 | Custom tags can also be applied globally: 43 | 44 | var qejs = require('qejs'); 45 | qejs.open = '{{'; 46 | qejs.close = '}}'; 47 | 48 | Which would make the following a valid template: 49 | 50 |

{{= title }}

51 | 52 | ## Unbuffered Code 53 | 54 | ``` 55 | <% code %> 56 | ``` 57 | 58 | QEJS supports exactly the same syntax as EJS for unbuffered code, usefull for conditionals, loops etc. 59 | 60 | ## Escapes HTML 61 | 62 | ``` 63 | <%= code %> 64 | ``` 65 | 66 | This differs from EJS in that if `code` returns a promise, it is resolved and then escaped before being outputted. While this is happening, QEJS will continue on to render the rest of the template, allowing many promised functions to be executed in parallel. 67 | 68 | ## Unescaped Buffering 69 | 70 | ``` 71 | <%- code %> 72 | ``` 73 | 74 | If `code` isn't a promise, this will work exactly like EJS, but if `code` is a promise, we will resolve it, before outputting the resolved value. We won't do any escaping on this value, so only use for trusted values, not user input. 75 | 76 | ## Async Blocks 77 | 78 | ``` 79 | <% promise -> value %>...Use value here...<% <- %> 80 | <% PromiseForAnArray -> [valueA, valueB, valueC...] %>...Use values individually here...<% <- %> 81 | <% [promiseA,promiseB,promiseC...] -> values %>...Use identifier as an array of resolved values...<% <- %> 82 | <% [promiseA,promiseB,promiseC...] -> [valueA,valueB,valueC...] %>...Use values individually here...<% <- %> 83 | ``` 84 | 85 | Async blocks are considered a relatively advanced feature, and where possible you should try and tick to just returning promises through `<%= code %>` as it's much easier to write that without creating bugs. 86 | 87 | Having said that, async blocks are not difficult to write and I hope you'll end up really loving them for those times when you really need them. 88 | 89 | What happens in an async block is we reserve a space for whatever text is outputted by the block, allowing you to use any QEJS inside the async block (including another async block). We then resolve the value of the promise you give us, and we give it the name you specify on the right hand side of the arrow operator. The async block starter must go in its own separate unbuffered code block, but you could put other things like comments inside the block with the end marker. 90 | 91 | Once you go past the end marker of an async block, you will no longer have access to the value of the promise. This lets us run lots of calls in parallel, and means that you can use async blocks inside `if` statments, `for` statements, `while` statements, `function` statements, pretty much anywhere you could write regular EJS. 92 | 93 | ## Inheritance and Partials 94 | 95 | QEJS supports both inheritance and partials. Inheritance is used to include the current template in the middle of some other template (similar to express's layout templates except a little more powerful). Currently this only works if you use the renderFile method (or render in express with the following snippet to setup). 96 | 97 | ### Inheritance 98 | 99 | Inheritance allows you to support features similar to those in express's layout template. To use a layout for a template, simply call `inherits('relative/path/to/template')` anywhere in your template that is not run asyncronously. That is to say, it can't go inside an async block, or inside the then callback of a promise. Usually it's best to put it at the top of your file. If you call it multiple times, it will throw an exception. 100 | 101 | views/foobar.html 102 | 103 | ```html 104 | <% inherits('layouts/navigation') %> 105 |

The great page foobar

106 | ``` 107 | 108 | layouts/navigation 109 | 110 | ```html 111 | <% inherits('base') %> 112 | Home 113 | About 114 |
115 | <%- contents %> 116 |
117 | ``` 118 | 119 | layouts/base 120 | 121 | ```html 122 | 123 | 124 | 125 | 126 | Document 127 | 128 | 129 | <%- contents %> 130 | 131 | 132 | ``` 133 | 134 | Be careful not to inherit from yourself as this would create errors that never got caught if you create an infinite loop of inheritance. 135 | 136 | As you can see, paths are resolved in a very forgiving way. They are resolved relative to the current file, then relative to the parent directory of the current directory and so on up the tree until a file is found. It will try for files with extensions '.qejs', '.ejs' and '.html' in that order unless you specify an extension. 137 | 138 | ### Partials 139 | 140 | You can render a child template within the current template. By default, it does not currently have access to any local variables of the calling template, only those supplied in options. 141 | 142 | To use, simply call render anywhere in the parent template. 143 | 144 | layouts/base 145 | 146 | ```html 147 | 148 | 149 | 150 | 151 | Document 152 | 153 | 154 | <%- render('views/foobar', {message:'hello world'}) %> 155 | 156 | 157 | ``` 158 | 159 | ```html 160 |

<%= message %>

161 | ``` 162 | 163 | ## Newline slurping 164 | 165 | If you end any code block with a `-` even if it's an async block, we'll support newline slurping for you (`<% code -%>` or `<% -%>` or `<%= code -%>`, `<%- code -%>`, `<% promise -> result -%>` or `<% < -%>`) That is to say, we won't output the next new line after we see that symbol. QEJS never outputs a newline inside a code block. 166 | 167 | ## Filters 168 | 169 | QEJS doesn't support filters. Although in a way it seems a shame not to maintain 100% compatability with the syncronous form of EJS, I think that it's more important to keep this library lean. Filters don't really add a lot, you can always attach such methods to arrays yourself and use standard javascript syntax, I don't want to hurt the purity of EJS though, so I've chosen not to add this syntax (bloat). 170 | 171 | ## ExpressJS Integration 172 | 173 | This module is fully compatible with [express 3.0.0](https://github.com/visionmedia/express) via the [consolidate.js](https://github.com/visionmedia/consolidate.js) library. 174 | 175 | To use it you'll need to install both consolidate and QEJS. You can do this in a single command with: 176 | 177 | npm install consolidate qejs 178 | 179 | The following example demonstrates using QEJS in express: 180 | 181 | ```javascript 182 | var express = require('express') 183 | , cons = require('consolidate') 184 | , app = express(); 185 | 186 | // assign the swig engine to .html files 187 | app.engine('html', cons.qejs); 188 | 189 | // set .html as the default extension 190 | app.set('view engine', 'html'); 191 | app.set('views', __dirname + '/views'); 192 | 193 | var users = []; 194 | users.push({ name: 'tobi' }); 195 | users.push({ name: 'loki' }); 196 | users.push({ name: 'jane' }); 197 | 198 | app.get('/', function(req, res){ 199 | res.render('index', { 200 | title: 'Consolidate.js' 201 | }); 202 | }); 203 | 204 | app.get('/users', function(req, res){ 205 | res.render('users', { 206 | title: 'Users', 207 | users: users 208 | }); 209 | }); 210 | 211 | app.listen(3000); 212 | console.log('Express server listening on port 3000'); 213 | ``` 214 | 215 | If it doesn't work, be sure to make absolutely certain you've got the latest version of express, and make sure you have actually created a users.html and index.html view. 216 | 217 | ## Contribute 218 | 219 | Fork this repository to add features or: 220 | 221 | 222 | Flattr this 223 | 224 | ## License 225 | 226 | MIT 227 | -------------------------------------------------------------------------------- /test/ejs-fixtures/backslash.ejs: -------------------------------------------------------------------------------- 1 | \foo -------------------------------------------------------------------------------- /test/ejs-fixtures/backslash.html: -------------------------------------------------------------------------------- 1 | \foo -------------------------------------------------------------------------------- /test/ejs-fixtures/double-quote.ejs: -------------------------------------------------------------------------------- 1 |

<%= "lo" + 'ki' %>'s "wheelchair"

-------------------------------------------------------------------------------- /test/ejs-fixtures/double-quote.html: -------------------------------------------------------------------------------- 1 |

loki's "wheelchair"

-------------------------------------------------------------------------------- /test/ejs-fixtures/error.ejs: -------------------------------------------------------------------------------- 1 |
    2 | <% if (users) { %> 3 |

    Has users

    4 | <% } %> 5 |
-------------------------------------------------------------------------------- /test/ejs-fixtures/error.out: -------------------------------------------------------------------------------- 1 | ReferenceError: error.ejs:2 2 | 1|
    3 | >> 2| <% if (users) { %> 4 | 3|

    Has users

    5 | 4| <% } %> 6 | 5|
7 | 8 | users is not defined -------------------------------------------------------------------------------- /test/ejs-fixtures/include.css.ejs: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test/ejs-fixtures/include.css.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test/ejs-fixtures/include.ejs: -------------------------------------------------------------------------------- 1 |
    2 | <% pets.forEach(function(pet){ %> 3 | <% include pet %> 4 | <% }) %> 5 |
-------------------------------------------------------------------------------- /test/ejs-fixtures/include.html: -------------------------------------------------------------------------------- 1 |
    2 | 3 |
  • tobi
  • 4 | 5 |
  • loki
  • 6 | 7 |
  • jane
  • 8 | 9 |
-------------------------------------------------------------------------------- /test/ejs-fixtures/includes/menu-item.ejs: -------------------------------------------------------------------------------- 1 |
  • <% include menu/item %>
  • -------------------------------------------------------------------------------- /test/ejs-fixtures/includes/menu/item.ejs: -------------------------------------------------------------------------------- 1 | <%= title %> -------------------------------------------------------------------------------- /test/ejs-fixtures/menu.ejs: -------------------------------------------------------------------------------- 1 | <% var url = '/foo' -%> 2 | <% var title = 'Foo' -%> 3 | <% include includes/menu-item -%> 4 | 5 | <% var url = '/bar' -%> 6 | <% var title = 'Bar' -%> 7 | <% include includes/menu-item -%> 8 | 9 | <% var url = '/baz' -%> 10 | <% var title = 'Baz' -%> 11 | <% include includes/menu-item -%> -------------------------------------------------------------------------------- /test/ejs-fixtures/menu.html: -------------------------------------------------------------------------------- 1 |
  • Foo
  • 2 |
  • Bar
  • 3 |
  • Baz
  • -------------------------------------------------------------------------------- /test/ejs-fixtures/messed.ejs: -------------------------------------------------------------------------------- 1 |
      <%users.forEach(function(user){%>
    • <%=user.name%>
    • <%})%>
    -------------------------------------------------------------------------------- /test/ejs-fixtures/messed.html: -------------------------------------------------------------------------------- 1 |
    • tobi
    • loki
    • jane
    -------------------------------------------------------------------------------- /test/ejs-fixtures/newlines.ejs: -------------------------------------------------------------------------------- 1 |
      2 | <% users.forEach(function(user){ %> 3 |
    • <%= user.name %>
    • 4 | <% }) %> 5 |
    -------------------------------------------------------------------------------- /test/ejs-fixtures/newlines.html: -------------------------------------------------------------------------------- 1 |
      2 | 3 |
    • tobi
    • 4 | 5 |
    • loki
    • 6 | 7 |
    • jane
    • 8 | 9 |
    -------------------------------------------------------------------------------- /test/ejs-fixtures/no.newlines.ejs: -------------------------------------------------------------------------------- 1 |
      2 | <% users.forEach(function(user){ -%> 3 |
    • <%= user.name %>
    • 4 | <% }) -%> 5 |
    -------------------------------------------------------------------------------- /test/ejs-fixtures/no.newlines.html: -------------------------------------------------------------------------------- 1 |
      2 |
    • tobi
    • 3 |
    • loki
    • 4 |
    • jane
    • 5 |
    -------------------------------------------------------------------------------- /test/ejs-fixtures/para.ejs: -------------------------------------------------------------------------------- 1 |

    hey

    -------------------------------------------------------------------------------- /test/ejs-fixtures/pet.ejs: -------------------------------------------------------------------------------- 1 |
  • <%= pet.name %>
  • -------------------------------------------------------------------------------- /test/ejs-fixtures/single-quote.ejs: -------------------------------------------------------------------------------- 1 |

    <%= 'loki' %>'s wheelchair

    -------------------------------------------------------------------------------- /test/ejs-fixtures/single-quote.html: -------------------------------------------------------------------------------- 1 |

    loki's wheelchair

    -------------------------------------------------------------------------------- /test/ejs-fixtures/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | foo: '<%= value %>'; 3 | } -------------------------------------------------------------------------------- /test/ejs-fixtures/user.ejs: -------------------------------------------------------------------------------- 1 |

    {= name}

    -------------------------------------------------------------------------------- /test/ejs.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Module dependencies. 3 | */ 4 | 5 | var ejs = require('..') 6 | , fs = require('fs') 7 | , read = fs.readFileSync 8 | , assert = require('should') 9 | , Q = require('q'); 10 | 11 | function fixturePath(name) { 12 | return __dirname + '/ejs-fixtures/' + name; 13 | } 14 | /** 15 | * Load fixture `name`. 16 | */ 17 | 18 | function fixture(name) { 19 | return read(fixturePath(name), 'utf8').replace(/\r\n/g, '\n'); 20 | } 21 | 22 | /** 23 | * User fixtures. 24 | */ 25 | 26 | var users = []; 27 | users.push({ name: 'tobi' }); 28 | users.push({ name: 'loki' }); 29 | users.push({ name: 'jane' }); 30 | 31 | (function (it) { 32 | describe('ejs.compile(str, options)', function(){ 33 | it('should compile to a function', function(){ 34 | var fn = ejs.compile('

    yay

    '); 35 | return fn().then(function (val) { 36 | val.should.equal('

    yay

    '); 37 | }); 38 | }) 39 | 40 | it('should allow customizing delimiters', function(res){ 41 | var fn = ejs.compile('

    {= name }

    ', { open: '{', close: '}' }); 42 | res.push(fn({ name: 'tobi' }).then(function (val) { 43 | val.should.equal('

    tobi

    '); 44 | })); 45 | 46 | var fn = ejs.compile('

    ::= name ::

    ', { open: '::', close: '::' }); 47 | res.push(fn({ name: 'tobi' }).then(function (val) { 48 | val.should.equal('

    tobi

    '); 49 | })); 50 | 51 | var fn = ejs.compile('

    (= name )

    ', { open: '(', close: ')' }); 52 | res.push(fn({ name: 'tobi' }).then(function (val) { 53 | val.should.equal('

    tobi

    '); 54 | })); 55 | }) 56 | 57 | it('should default to using ejs.open and ejs.close', function(res){ 58 | ejs.open = '{'; 59 | ejs.close = '}'; 60 | var fn = ejs.compile('

    {= name }

    '); 61 | res.push(fn({ name: 'tobi' }).then(function (val) { 62 | val.should.equal('

    tobi

    '); 63 | })); 64 | 65 | var fn = ejs.compile('

    |= name |

    ', { open: '|', close: '|' }); 66 | res.push(fn({ name: 'tobi' }).then(function (val) { 67 | val.should.equal('

    tobi

    '); 68 | })); 69 | 70 | return Q.all(res).then(function () { 71 | delete ejs.open; 72 | delete ejs.close; 73 | }); 74 | }) 75 | }) 76 | 77 | describe('ejs.render(str, options)', function(){ 78 | it('should render the template', function(){ 79 | return ejs.render('

    yay

    ').then(function (val) { 80 | val.should.equal('

    yay

    '); 81 | }); 82 | }) 83 | 84 | it('should accept locals', function(){ 85 | return ejs.render('

    <%= name %>

    ', { name: 'tobi' }).then(function (val) { 86 | val.should.equal('

    tobi

    '); 87 | }); 88 | }) 89 | }) 90 | 91 | describe('ejs.renderFile(path, options, fn)', function(){ 92 | it('should render a file', function(){ 93 | return ejs.renderFile(fixturePath('para.ejs')).then(function (html){ 94 | html.should.equal('

    hey

    '); 95 | }); 96 | }) 97 | 98 | it('should accept locals', function(){ 99 | var options = { name: 'tj', open: '{', close: '}' }; 100 | return ejs.renderFile(fixturePath('user.ejs'), options).then(function (html) { 101 | html.should.equal('

    tj

    '); 102 | }); 103 | }) 104 | }) 105 | 106 | describe('<%=', function(){ 107 | it('should escape', function(){ 108 | return ejs.render('<%= name %>', { name: '