Quick hack: Add a dynamic Table of Contents to a Ghost Blog

When I published the Professional Australian Glossary I decided to add a table of contents. It was a large article. But I thought... there's got to be a way of automating this. And if there isn't, I'll build one!

Pieces this together from around the web, but had to redo it a bit to make it work in Ghost.

Step 1

Add a <span> tag up where you want the ToC to go with its own id, in its own HTML block. I chose <span id="dynamictoc"></span>.

Step 2

You'll need JQuery. There's probably an easier way, but this was the easiest easy way.

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=" crossorigin="anonymous"></script>

Don't use this exact code, use whatever you find at https://cdnjs.com/libraries/jquery/.

Step 3

Put this code at the bottom in an HTML block. This looks through the code and finds all the headings (tagged with h1... did you use headings?) and creates the contents.

<script>
	var ToC = "<nav role='navigation' class='table-of-contents'><ul>";
	$("article h1").each(function() {
		var el = $(this);
        var title = el.text();
		var link = "#" + el.attr("id");
		ToC += "<li><a href='" + link + "'>" + title + "</a></li>";
	});
	ToC += "</ul></nav>";
    console.log(ToC);
	$("#dynamictoc").html(ToC);
</script>