Skip to content

Instantly share code, notes, and snippets.

@artibella
Created January 19, 2017 20:06
Show Gist options
  • Save artibella/724b5473f6bd8462d6bd46928226fe01 to your computer and use it in GitHub Desktop.
Save artibella/724b5473f6bd8462d6bd46928226fe01 to your computer and use it in GitHub Desktop.
Use Fractal as a custom Express view engine
// example Express server using the custom Fractal view engine
const express = require('express');
const path = require('path');
const appRoot = path.normalize(path.join(__dirname, '..'));
const app = express();
const fractalEngine = require(path.join(appRoot, 'lib/fractal-engine'));
const loadComponents = require(path.join(appRoot, 'middleware/load-components'));
// register custom Fractal rendering engine
app.engine('fractal', fractalEngine);
// use Fractal as rendering engine
app.set('view engine', 'fractal');
app.set('views', appRoot + '/views');
// all static files belong in public
app.use(express.static(path.join(appRoot, 'public')));
// add Fractal components middleware
app.use(loadComponents);
// add routes
const exampleRoute = require('./example-route');
app.use(exampleRoute);
module.exports = app;
const router = require('express').Router()
const fixture = require('../../data/fixture.json');
const render = (request, response) => {
const component = '@page'; // the component handle you want to render
const context = fixture; // the context data for the component
response.render('index', {
component: component,
context: context
});
};
router.get('/', (request, response) => {
render(request, response);
});
module.exports = router;
const fs = require('fs');
const fractal = require('path/to/fractal');
/**
* Simple view engine using the Fractal API for component rendering
* based on https://expressjs.com/en/advanced/developing-template-engines.html
*
* @param {String} filePath Path to the view file
* @param {Object} options Render options
* Required fields: component and context
* @param {Function} callback Callback function
*
*/
const render = (filePath, options, callback) => {
const component = options.component;
const context = Object.assign({}, options.context);
fs.readFile(filePath, function (err, content) {
if (err) {
return callback(err);
}
fractal.components.render(component, context).then(html => {
content.toString().replace('{{yield}}', html);
return callback(null, html);
}).catch(error => {
return callback(err);
});
});
};
module.exports = render;
<!-- views/index.fractal which can be used as a layout file -->
{{yield}}
const fractal = require('path/to/fractal');
// Middleware to ensure that Fractal components are loaded
const loadComponents = function (req, res, next) {
if(!fractal.components.isLoaded) {
fractal.components.load().then(() => {
console.log('👍 Loaded Fractal components');
next();
});
} else {
next();
}
};
module.exports = loadComponents;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment