Making qr codes for jekyll pages

28 Dec 2020

While building hand made science I found myself making lots of printable things, especially lab sheets for practical work, question pages etc.

I thought it would be cool if you had a QR code on the question sheet which takes you to the page with the video and other blurb.

After googleling about for a bit and not finding a nice way to get Jekyll to run a script every time you build your site, I ended up making my own solution. I suspect this is massively clunky if you’re a Jekyll pro.

I added a variable to the front matter of pages I wanted QR codes for:

makeQRCode: true

Then I added this to my default template, so that it’s available on all pages.

1
2
3
4
5
<!-- 
{% if page.makeQRCode %}
_QR-"{{page.title}}".png  "https://www.handmadescience.co.uk{{page.url}}"
{% endif %}
-->

Line 3 gives me two useful things, a filename for the QR code, and the URL the QR needs to point to.

lines 1 and 5 are HTML comments that stop the text on line 3 from showing up on the site. Yes I could have deleted the line when I’m finished, that would have been nicer.

I added the underscore at the start of line 3 so Jekyll ignores the generated png files, otherwise they get added to the built _site folder.

Then I added the following script in QRMaker.sh:

#!/bin/zsh
cat _site/**/*.html | grep ^_QR- | xargs -n 2 qrencode -o 

Which gets called whenever I run my upload script.

the ** tells zsh to look in subfolders to any depth for html files, the ^ tells grep to only look for lines starting with the pattern. I also found I had to tell xargs to expect 2 arguments, hence -n 2

Only pages on which I’ve set makeQRCode: true will contain the line starting with "_QR-".

Finally It uses xargs to feed those two strings into the qrencode utility which will spit out a png for the relevant URL.

For completeness the upload script is:

#!/bin/zsh
JEKYLL_ENV=production bundle exec jekyll build && 
rsync -a _site/ [user]@[host]:handmadescience/
source QRMaker.sh

Qrencode can be downloaded easily, I’m on a mac so

brew install qrencode

Works fine.