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