Skip to content

Commit

Permalink
Merge branch 'oscarotero-master'
Browse files Browse the repository at this point in the history
  • Loading branch information
mde committed Apr 21, 2018
2 parents 9cfe8d5 + 9252132 commit 260f228
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 0 deletions.
18 changes: 18 additions & 0 deletions examples/output-function.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<ul>
<%
users.forEach(function (user) {
echo('<li>');
echo('<strong>' + user.name + '</strong>');
echo('is a ' + user.age + ' year old ' + user.species);
echo('</li>\n');
});
-%>
</ul>

<ul>
<%
users.forEach(function (user) {
echo(include('./partial.ejs', {user: user}));
});
%>
</ul>
22 changes: 22 additions & 0 deletions examples/output-function.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* Believe it or not, you can declare and use functions in EJS templates too.
*/

var ejs = require('../');
var read = require('fs').readFileSync;
var join = require('path').join;
var path = join(__dirname, '/output-function.ejs');
var data = {
users: [
{ name: 'Tobi', age: 2, species: 'ferret' },
{ name: 'Loki', age: 2, species: 'ferret' },
{ name: 'Jane', age: 6, species: 'ferret' }
]
};

var ret = ejs.compile(read(path, 'utf8'), {
filename: path,
outputFunctionName: 'echo'
})(data);

console.log(ret);
4 changes: 4 additions & 0 deletions examples/partial.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<li>
<strong><%= user.name %></strong>
is a <%= user.age %> year old <%= user.species %>
</li>
4 changes: 4 additions & 0 deletions lib/ejs.js
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,7 @@ function Template(text, opts) {
options.cache = opts.cache || false;
options.rmWhitespace = opts.rmWhitespace;
options.root = opts.root;
options.outputFunctionName = opts.outputFunctionName;
options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME;
options.views = opts.views;

Expand Down Expand Up @@ -551,6 +552,9 @@ Template.prototype = {
if (!this.source) {
this.generateSource();
prepended += ' var __output = [], __append = __output.push.bind(__output);' + '\n';
if (opts.outputFunctionName) {
prepended += ' var ' + opts.outputFunctionName + ' = __append;' + '\n';
}
if (opts._with !== false) {
prepended += ' with (' + opts.localsName + ' || {}) {' + '\n';
appended += ' }' + '\n';
Expand Down

0 comments on commit 260f228

Please sign in to comment.