Hacking Ghost Part 2

Fetching/modifying/deleting custom data natively in ghost to display on your custom pages.

Hacking Ghost Part 2
Photo by Jeremy Bezanger / Unsplash

In the previous article, I mentioned how to get custom routing in ghost and pass data to the handlebars template. You can read about it here.

The following will explain how to utilize the ghost's built-in database query tool to fetch, insert and edit data from the ghost database.

Ghost uses the NPM package knex. It's a library that supports MySQL databases and can support other databases so in the future if knex adds support for PostgreSQL, you can swap databases without changing any ghost source code.

Using knex

I am going to fetch a book list from the database. I inserted a table called books in my database using Phpmyadmin. I inserted the following data:

Next, I am going to create the file books.js and put it in the directory with the other data services:


Now you can edit the site.js the file you modified earlier to include this books.js file and to fetch the data before passing it to handlebars.

Updating Handlebars

Lastly, you need to update the template, so head over to the books.hbs you created earlier and update it to the following code:


The final result:


This data is uncached. Feel free to install a cache layer for cpu-intensive pages.

To change the title of the page, you can pass the variable directly meta_title as below:

- Gib