Add client side ejs compiled with express middleware example
Mark Smith
5 years ago
|
0 |
```
|
|
1 |
npm install
|
|
2 |
npm start
|
|
3 |
open http://localhost:3000
|
|
4 |
```
|
|
0 |
var express = require('express');
|
|
1 |
var path = require('path');
|
|
2 |
var ejs = require('ejs');
|
|
3 |
|
|
4 |
var app = express();
|
|
5 |
app.set('views', path.join(__dirname, 'views'));
|
|
6 |
app.set('view engine', 'ejs');
|
|
7 |
|
|
8 |
function compileEjsTemplate(name, template) {
|
|
9 |
const compiledTemplate = ejs.compile(template, {
|
|
10 |
client: true,
|
|
11 |
outputFunctionName: name
|
|
12 |
});
|
|
13 |
return function compileEjsTemplate(req, res, next) {
|
|
14 |
res.locals.compiledEjsTemplates = res.locals.compiledEjsTemplates || {};
|
|
15 |
res.locals.compiledEjsTemplates[name] = compiledTemplate.toString();
|
|
16 |
return next();
|
|
17 |
}
|
|
18 |
}
|
|
19 |
|
|
20 |
app.use(compileEjsTemplate('helloTemplate', "Hello <%= include('messageTemplate', { person: 'John' }); %>"));
|
|
21 |
app.use(compileEjsTemplate('messageTemplate', "<%= person %> now you know <%= fact %>."));
|
|
22 |
app.use('/', function(req, res, next) {
|
|
23 |
return res.render('index', {});
|
|
24 |
});
|
|
25 |
|
|
26 |
app.listen(process.env.PORT || 3000);
|
|
0 |
{
|
|
1 |
"description": "client side ejs compiled with express middleware",
|
|
2 |
"main": "app.js",
|
|
3 |
"scripts": {
|
|
4 |
"start": "node ./app.js"
|
|
5 |
},
|
|
6 |
"dependencies": {
|
|
7 |
"ejs": "^2.6.1",
|
|
8 |
"express": "~4.16.0"
|
|
9 |
}
|
|
10 |
}
|
|
0 |
<!DOCTYPE html>
|
|
1 |
<html>
|
|
2 |
<head>
|
|
3 |
<title>ejs client-side</title>
|
|
4 |
</head>
|
|
5 |
<body>
|
|
6 |
<div id="greeting"></div>
|
|
7 |
<script>
|
|
8 |
const helloTemplateFn = <%- compiledEjsTemplates.helloTemplate %>;
|
|
9 |
const messageTemplateFn = <%- compiledEjsTemplates.messageTemplate %>;
|
|
10 |
|
|
11 |
(function() {
|
|
12 |
const includeFn = function(path, data) {
|
|
13 |
if (path === 'messageTemplate') {
|
|
14 |
return messageTemplateFn({
|
|
15 |
fact: 'how to render a page with compiled ejs templates',
|
|
16 |
person: data.person
|
|
17 |
});
|
|
18 |
}
|
|
19 |
};
|
|
20 |
|
|
21 |
const html = helloTemplateFn({}, null, includeFn, null);
|
|
22 |
const $greeting = document.getElementById('greeting');
|
|
23 |
$greeting.innerHTML = html;
|
|
24 |
})();
|
|
25 |
</script>
|
|
26 |
</body>
|
|
27 |
</html>
|