Skip to content

Instantly share code, notes, and snippets.

@ninjasort
Created February 5, 2015 01:29
Show Gist options
  • Save ninjasort/d21717ca017ea7008df5 to your computer and use it in GitHub Desktop.
Save ninjasort/d21717ca017ea7008df5 to your computer and use it in GitHub Desktop.
Rendering React templates in a Keystone View
var keystone = require('keystone');
var async = require('async');
var _ = require('underscore');
var React = require('react');
// install node-jsx
require('node-jsx').install({extension: '.js', harmony: true});
// require React component and use React.createFactory to configure it later
var BlogPage = React.createFactory(require('../../components/blogPage'));
exports = module.exports = function(req, res) {
var view = new keystone.View(req, res),
locals = res.locals;
// Init locals
locals.section = 'blog';
locals.filters = {
category: req.params.category
};
locals.data = {
posts: [],
categories: []
};
// helper function to create React templates from admin data
function createReactTemplates (data) {
var templates = _.map(data.results, function (post) {
var component = BlogPage({
isPreview: true,
title: post.title,
image: post.image,
slug: post.slug,
date: post.publishedDate,
categories: post.categories,
content: post.content,
author: post.author,
demo: post.demo
});
// return a rendered html string
return {
postTpl: React.renderToString(component)
}
});
return templates;
}
// Load the posts
view.on('init', function(next) {
var q = keystone.list('Post').paginate({
page: req.query.page || 1,
perPage: 10,
maxPages: 10
});
q.exec(function(err, results) {
// create templates from each post
var templates = createReactTemplates(results);
locals.data.posts = templates;
next(err);
});
});
// Render the view
view.render('blog');
};
@TheDucc
Copy link

TheDucc commented Apr 20, 2015

Any chance of seeing what the file ../../components/blogPage looks like?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment