Skip to content

Commit

Permalink
Merge pull request #409 from mjgs/client-side-ejs-compiled-with-express
Browse files Browse the repository at this point in the history
Client side ejs compiled with express middleware example
  • Loading branch information
mde committed Nov 19, 2018
2 parents 59ac6ef + 12ca920 commit 20d4c77
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -244,6 +244,8 @@ Most of EJS will work as expected; however, there are a few things to note:
}); // returns rendered string
```

See the [examples folder](https://github.com/mde/ejs/tree/master/examples) for more details.

### IDE Integration with Syntax Highlighting

VSCode:Javascript EJS by *DigitalBrainstem*
Expand Down
5 changes: 5 additions & 0 deletions examples/express/README.md
@@ -0,0 +1,5 @@
```
npm install
npm start
open http://localhost:3000
```
27 changes: 27 additions & 0 deletions examples/express/app.js
@@ -0,0 +1,27 @@
var express = require('express');
var path = require('path');
var ejs = require('ejs');

var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

function compileEjsTemplate(name, template) {
const compiledTemplate = ejs.compile(template, {
client: true,
outputFunctionName: name
});
return function compileEjsTemplate(req, res, next) {
res.locals.compiledEjsTemplates = res.locals.compiledEjsTemplates || {};
res.locals.compiledEjsTemplates[name] = compiledTemplate.toString();
return next();
};
}

app.use(compileEjsTemplate('helloTemplate', 'Hello <%= include(\'messageTemplate\', { person: \'John\' }); %>'));
app.use(compileEjsTemplate('messageTemplate', '<%= person %> now you know <%= fact %>.'));
app.use('/', function(req, res) {
return res.render('index', {});
});

app.listen(process.env.PORT || 3000);
11 changes: 11 additions & 0 deletions examples/express/package.json
@@ -0,0 +1,11 @@
{
"description": "client side ejs compiled with express middleware",
"main": "app.js",
"scripts": {
"start": "node ./app.js"
},
"dependencies": {
"ejs": "^2.6.1",
"express": "~4.16.0"
}
}
28 changes: 28 additions & 0 deletions examples/express/views/index.ejs
@@ -0,0 +1,28 @@
<!DOCTYPE html>
<html>
<head>
<title>client side ejs compiled with express middleware</title>
</head>
<body>
<div id="greeting"></div>
<script>
const helloTemplateFn = <%- compiledEjsTemplates.helloTemplate %>;
const messageTemplateFn = <%- compiledEjsTemplates.messageTemplate %>;
(function() {
const includeFn = function(path, data) {
if (path === 'messageTemplate') {
return messageTemplateFn({
fact: 'how to render a page with compiled ejs templates',
person: data.person
});
}
};
const html = helloTemplateFn({}, null, includeFn, null);
const $greeting = document.getElementById('greeting');
$greeting.innerHTML = html;
})();
</script>
</body>
</html>

0 comments on commit 20d4c77

Please sign in to comment.