Strip url to 1 word in Jekyll

html, jekyll, liquid, static-site

Solution

I managed to solve it with three filters:

{{ page.url | replace:'/',' ' | truncatewords: 1 | remove:'...' }}

`page.url` outputs: `/page/cat/title`, then `replace` removes the forward slashes producing: `page cat title`. `truncatewords` truncates the string down to one word, producing: `page...` (for some reason three dots gets inserted after the remaining word). After all this I only needed to remove those dots with `remove` and voilá, my final string: `page`.

Hope this helps someone.

Problem

I am building a Jekyll blog, and I have come across an issue with permalinks. My permalinks to blog posts are set like this in _config.yml: ``` permalink: /:page/:categories/:title ``` It outputs like this when navigating to a blog post: ``` http://localhost:4000/blog/travel/netherlands-trip-prequesites/ ``` I have some static pages in the site: Blog, Travel The variable `page.url` outputs this url: `/blog/travel/netherlands-trip-prequesites` The code my navigation bar uses to highlight the current page (giving it an "active" class): ``` {% assign url = page.url|remove:'index.html' %} {% for nav in site.navigation %} {% if nav.href == url %} <li class="active"><a href="{{nav.href}}">{{nav.name}}</a></li> {% else %} <li><a href="{{nav.href}}">{{nav.name}}</a></li> {% endif %} {%endfor%} ``` It works great when navigating to static pages, however when I click a blog post it doesn't highlight the correct static page. (ex.: If i navigate to a blog post with the url `/blog/smth/title` it should automatically highlight "Blog" in my navigation. When I navigate to `/travel/smth/title` it should highlight "Travel") What I'd like to do is to strip down the output of page.url to its first part. For example I'd like to stip the following output ``` /blog/travel/netherlands-trip-prequesites ``` down to ``` /blog/ ``` Why? So I can use it to check which static page it belongs to and highlight it accordigly.

Original source