Node.js / Express
In the Node ecosystem, we can create a view helper that renders EJS components (or Pug/Handlebars) and compiles them for PulsePoint on the fly.
Express Integration Demo
Ep. 06
Node.js
Express
EJS Component Loader
04:20
The Implementation
server.js
const express = require('express');
const ejs = require('ejs');
const path = require('path');
const fs = require('fs');
const app = express();
app.set('view engine', 'ejs');
// 1. The Component Helper
app.locals.component = (name, data = {}) => {
// Read the component file
const viewPath = path.join(__dirname, 'views', 'components', `${name}.ejs`);
const template = fs.readFileSync(viewPath, 'utf-8');
// Render EJS to HTML string
const rendered = ejs.render(template, data);
// 2. Transform <script> to <script type="text/pp">
// This stops the browser from running it immediately
return rendered.replace(
/<script(?![^>]*\btype=)/g,
'<script type="text/pp"'
);
};
app.get('/', (req, res) => {
// Pass initial data from DB/API
res.render('index', {
user: { name: 'Node Ninja', role: 'admin' }
});
});
app.listen(3000);
views/index.ejs
<h1>Welcome</h1>
<!-- Render Component -->
<!-- Notice the "-" to render unescaped HTML -->
<%- component('profile-card', { user }) %>
<!-- views/components/profile-card.ejs -->
<div class="card">
<h3>User: {username}</h3>
<p>Role: {role}</p>
<script>
// Node props injected into Client State
const [username] = pp.state("<%= user.name %>");
const [role] = pp.state("<%= user.role %>");
</script>
</div>