Skip to content

Instantly share code, notes, and snippets.

@tnajdek
Created March 31, 2015 18:36
Show Gist options
  • Save tnajdek/84169ad5f55f0d23d526 to your computer and use it in GitHub Desktop.
Save tnajdek/84169ad5f55f0d23d526 to your computer and use it in GitHub Desktop.
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