Table of Contents Tutorial for Casper Version 4 - Simplified

TO ADD A TOC (Table of Contents) IN THE CASPER THEME …

1. Paste this into your Site Header Code Injection

<!-- Tocbot Stylesheet -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.10.0/tocbot.css" />

<!-- Tocbot Inline CSS (Specific Adjustments for the Casper Theme) -->
<style>
/* Offset headings from fixed header */
.post-content h2::before,
.post-content h3::before {
    display: block;
    content: " ";
    height: 84px;
    margin-top: -84px;
    visibility: hidden;
}

/* Adjust content wrapper */
.post-content {
    display: block;
}

/* Adjustments to wide and full width cards */
.kg-gallery-card,
.kg-width-wide,
.kg-width-full {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.kg-gallery-card > *,
.kg-width-wide > *,
.kg-width-full > *,
figure.kg-width-full img {
    margin-left: -50vw;
    margin-right: -50vw;
}

.post-full-content pre {
    max-width: 0;
}

    /* Add a light gray box (Optional) */
    .toc {
        border: 1px solid #a2a9b1;
        background-color: #f8f9fa;
        padding: 5px;
    }
</style>

2. Paste this into your Site Footer Code Injection

<!-- Tocbot Script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.10.0/tocbot.min.js"></script>
<script>
    tocbot.init({
        tocSelector: '.toc',
        contentSelector: 'section.gh-content.gh-canvas',
        hasInnerContainers: true
    });
</script>

3. Paste this HTML snippet where you want the Table of Contents to appear

<aside class="toc"></aside>

4. For quick testing, you can navigate to a post (one with some headings) in Ghost admin and create a new HTML card in the area you want your table of contents to appear. A HTML card can be added using the “ + ” button or by typing “/HTML” and hitting enter.

Within the HTML card paste the HTML snippet:

<aside class="toc"></aside>

Then click save and view the post. The snippet you’ve added to the post should now contain a table of contents created from all the headings in that post :raised_hands:.

5. To get the TOC working on all of your site’s post and/or pages, paste the HTML snippet in your post.hbs and/or in page.hbs, or in any other template where you want the TOC to appear for every post and/or page.

5 Likes