Added support for template.renderSync()

This commit is contained in:
Patrick Steele-Idem 2014-07-19 13:24:13 -06:00
parent 68a76ad132
commit 8b139199b2
6 changed files with 68 additions and 1 deletions

View File

@ -15,6 +15,7 @@ Raptor Templates is an extensible, streaming, asynchronous, [high performance](h
- [Template Rendering](#template-rendering)
- [Callback API](#callback-api)
- [Streaming API](#streaming-api)
- [Synchronous API](#synchronous-api)
- [Asynchronous Render Context API](#asynchronous-render-context-api)
- [Browser-side Rendering](#browser-side-rendering)
- [Using the RaptorJS Optimizer](#using-the-raptorjs-optimizer)
@ -265,6 +266,20 @@ template.render({
```
_NOTE:_ This will end the target output stream.
### Synchronous API
If you know that your template rendering requires no asynchronous rendering then you can use the synchronous API to render a template to a String:
```javascript
var template = require('raptor-templates').load('template.rhtml');
var output = template.renderSync({
name: 'Frank',
count: 30
});
console.log('Output HTML: ' + output);
```
### Asynchronous Render Context API
```javascript

View File

@ -60,6 +60,13 @@ function Template(renderFunc) {
}
Template.prototype = {
renderSync: function(data) {
var context = new Context();
context.sync();
this._(data, context);
context.end();
return context.getOutput();
},
render: function(data, context, callback) {
if (data == null) {
data = {};

View File

@ -193,5 +193,47 @@ describe('raptor-templates/api' , function() {
});
});
it('should allow a template to be rendered to a string synchronously using renderSync', function() {
var template = raptorTemplates.load(nodePath.join(__dirname, 'test-project/hello.rhtml'));
var output = template.renderSync({ name: 'John' });
expect(output).to.equal('Hello John!');
});
it('should throw an error if beginAsync is used with renderSync', function() {
var template = raptorTemplates.load(nodePath.join(__dirname, 'test-project/hello-async.rhtml'));
var output;
var e;
try {
output = template.renderSync({
nameDataProvider: function(arg, callback) {
setTimeout(function() {
callback(null, 'John');
}, 100);
}
});
} catch(_e) {
e = _e;
}
expect(output).to.equal(undefined);
expect(e).to.not.equal(undefined);
});
it('should throw errors correctly with renderSync', function() {
var template = raptorTemplates.load(nodePath.join(__dirname, 'test-project/hello-error.rhtml'));
var output;
var e;
try {
output = template.renderSync();
} catch(_e) {
e = _e;
}
expect(output).to.equal(undefined);
expect(e).to.not.equal(undefined);
});
});

View File

@ -392,5 +392,4 @@ describe('raptor-templates/rhtml' , function() {
it("should support scanning a directory for tags", function(done) {
testRender("test-project/rhtml-templates/scanned-tags.rhtml", {}, done);
});
});

View File

@ -0,0 +1,3 @@
<async-fragment data-provider="$data.nameDataProvider" var="name">
Hello $name!
</async-fragment>

View File

@ -0,0 +1 @@
{% throw new Error('Test'); %}