Instantly share code, notes, and snippets.

Embed
What would you like to do?
Assemble plugin to automatically generate and attach ids and anchor links to headers
/*eslint-env node */
var cheerio = require('cheerio'),
htmlStrip = require('htmlstrip-native');
var options = {
stage: 'render:post:page'
};
module.exports = function (params, callback) {
'use strict';
var $ = cheerio.load(params.content);
var headings = $('h3,h4,h5,h6');
headings.map(function(index, element) {
var $element = $(element);
if(!element.attribs.id) {
var id = $element.text();
id = htmlStrip.html_strip(id);
id = id.replace(/"/g, "\\\"");
$element.attr('id', id);
$element.addClass('anchor');
$('<a>').attr('href', '#' + id).addClass('icon-link').insertAfter($element);
}
});
params.content = $.html();
callback();
};
module.exports.options = options;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment