Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Node.js script to render octicons with a Handlebars template custom helper
const handlebars = require('express-handlebars');
const express = require('express');
// Directory where your compiled octicons are,
// more info on this @ https://github.com/primer/octicons#usage
const octicons = require('/home/nodeassets/octicons/index.js');
function loadServer(){
// Load express here
var app = express();
var hbs = handlebars.create({
defaultLayout: 'main'
});
hbs.helpers = loadHelpers(hbs.handlebars);
// Suppose app is our express instance
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
// Load requests here, ex:
app.get('/test', function(req, res){
res.render('test');
});
}
function loadHelpers(Handlebars){
return {
octicon: function(name, className, height, width){
var octicon = octicons[name];
if (!octicon){
return '';
}
var options = {
'class': (typeof className === 'string' ? 'octicon-' + className : ''),
height: (typeof height === 'number' ? height : octicon.height),
width: (typeof width === 'number' ? width : octicon.width)
};
if (height && typeof width !== 'number'){
var originHeight = parseInt(octicon.height);
var originWidth = parseInt(octicon.width);
// If we don't have a width, rescale correctly
options.width = Math.floor(originWidth * (height / originHeight));
}
return new Handlebars.SafeString(octicon.toSVG(options));
}
};
}
loadServer();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Octicon Test</title>
</head>
<body>
{{ octicon 'person' 'white' }}
{{ octicon 'server' 'dark' 25 }}
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment