Last active
October 2, 2016 15:27
-
-
Save hugmanrique/b63ff4b88c6ca2a9b52e38d41db3be81 to your computer and use it in GitHub Desktop.
Node.js script to render octicons with a Handlebars template custom helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment