3 June 2017

Making sense of URLs in GitHub Pages for projects

I used GitHub Pages’ site.github.public_repositories to list all my public Repositories. I wanted to list pages in a Collection in a similar way for the solvahol/ghkb project. Because GitHub Pages addresses the project as a subdirectory of the owner’s Pages site, this was less straightforward than I expected.

Here are my notes about what I found and how I made sense of it. Here’s the general solution I arrived at:

  1. Create a project Repository on GitHub, configured to serve GitHub Pages
  2. Configure a Jekyll Collection and add content
  3. Customize the permalink URL for pages in the collection
  4. Use site.github.url to prepend the Pages URL in links

ilovesymposia.com summarizes several caveats of letting GitHub Pages render Jekyll sites, including the challenge of writing URLs for links in a project’s Pages site.

He points to the Jekyll documentation, which recommends using site.github.url to prepend the project site URL in links.

Basic setup

If you want to see your changes before you publish them, render the site locally with jekyll serve. The project repository doesn’t exist locally so you’ll see a-file.html rendered at http://localhost:4000/my-collection/a-file.html.

This can present a problem because it may work locally and fail when pushed to GitHub:

<ul>
{% for a-page in site.coll-name %}
    <li>
        <a href="{{ a-page.url }}">{{ a-page.title }}</a>
        {{ a-page.excerpt }}
    </li>
{% endfor %}
</ul>

That code will create a link to /my-collection/a-file.html, which won’t work in owner/repo because it’s missing /repo at the beginning. If you write in the /repo that won’t work when you test locally.

One solution for this problem is to write links using site.github.url to fill the beginning of the URL:

<ul>
{% for a-page in site.coll-name %}
    <li>
        <a href="{{ site.github.url }}{{ a-page.url }}">{{ a-page.title }}</a>
        {{ a-page.excerpt }}
    </li>
{% endfor %}
</ul>

That code will fill in the beginning of the URL when rendered on GitHub, and will leave it out when rendered locally.

comments? | contribute | tags: notes gh-pages jekyll