Create an Index page for Grav, from blog posts


Create an Index page for Grav, from blog posts

When a website, gets large enough, finding posts and navigating, gets frustrating. Something to help, is to create an Index page. A page, that will have a list of all blog posts, in chronological order, easy for someone to read and find what he is looking for. And because Grav CMS keeps everything in files, it's a bit easier for us to make this happen.

The solution is simple. We will make a couple of scripts, that will navigate into the Grav folders, extract the Title and Timestamp of each blog post and add the info into a new site page. For this i created two scripts. One to get the list of the posts and create the markdown text to add to the page and another one, to manipulate the Index page and add the list, we get with the other script. It could be done, in one script, but because manipulating the site page is a bit dangerous, i didn't want to change something by accident, if i was just wanted to change the text format ot the Index list. Anyways...

The two script are below. Make sure, to put the correct paths for your site/files. Also notice that, depending of the type of the page, Grav, sometimes names the markdown file as item.md and other times as default.md. So, make sure to put the right one.

So...

  • copy/paste the script into the folder you prefer.
  • create the main index page for the site and mark the folder of it and the file it uses (either item.md or default.md)
  • edit the script and enter the correct paths for the blog folder and the file for the index page
  • make the scripts execute-able with chmod +x <scriptname>
  • execute the second script

You can see the result in the Index page, at the sidebar of the website.

#!/bin/bash

# Define your blog folder
cd ./user/pages/04.blog

for D in *; do
    if [ -d "${D}" ]; then
        cd "$D"

        if [ -f item.md ]; then
          TEXT="$(cat item.md)"
        else
          TEXT="$(cat default.md)"
        fi
        #title
        TITLE="$(echo "$TEXT" | grep ^title: | cut -d"'" -f2)"
        #url
        URL="$(echo "$TEXT" | grep og:url | cut -d"'" -f4)"
        #date
        DT="$(echo "$TEXT" | grep lastmod | cut -d"'" -f2)"
        KW="$(echo "$TEXT" | grep keywords -m1 | cut -d"'" -f2)"

        #echo -e "- [$TITLE]($URL) | $DT | {c:#888888}tags: $KW{/c}"
        echo -e "- [$TITLE]($URL) | $DT"
        cd ..
    fi
done
#!/bin/bash
DIR="./user/pages/05.blog-index"
FILE="$DIR/default.md"
LN=$(grep -n "\-\-\-" $FILE | tail -1 | cut -d":" -f1)
cat $FILE | head -$LN > $DIR/newfile.md
echo " " >> $DIR/newfile.md
./blogindex.sh >> $DIR/newfile.md

mv $DIR/newfile.md $FILE

Add a comment

Previous