Travis
Travis

Reputation: 14486

Dynamically add and filter images in Jekyll for github pages?

I am trying out Jekyll to help someone who's not all that technical maintain their own static site. I would like to be able to have a images directory in the app's root /images containing images following a naming convention:

post_one_1.jpg, post_one_2.jpg, post_two_1.jpg, post_two_2.jpg ... etc.

I would then like for the user to create a post (post_one) and dynamically grab all of the images pertaining to that post from the images directory.

This plugin (https://gist.github.com/jgatjens/8925165) does almost exactly what I need, but isn't compatible with github pages.

Is there a solution in which I can hand the site off to a user and they would only need to add images to the image directory following the naming convention and then create a post and have access to the images?

Upvotes: 2

Views: 899

Answers (1)

David Jacquel
David Jacquel

Reputation: 52829

Given you have a post file _posts/2015-05-28-post_one.md

From inside this post you have :

  • page.id = /2015/05/29/post_one
  • page.dir = /2015/05/29

In order to extract post_one whe do :

{% assign imgNameStart = page.id | remove: page.dir | remove: "/" %}

We now generate the base path we search for :

{% assign imgBasePath = imgNameStart | prepend: "/images/" %}

in this case it will be imgBasePath = "/images/post_one"

Loop over all our static files (files that are not pages or posts).

{% for img in site.static_files %}

And print images that have /images/post_one in their path like /images/post_one-01.jpg or /images/post_one-wathever-you-want.jpg

{% if img.path contains imgBasePath %}
<img src="{{ site.baseurl }}{{ img.path }}">
{% endif %}
{% endfor %}

All together :

{% assign imgNameStart = page.id | remove: page.dir | remove: "/" %}
{% assign imgBasePath = imgNameStart | prepend: "/images/" %}
{% for img in site.static_files %}
{% if img.path contains imgBasePath %}
<img src="{{ site.baseurl }}{{ img.path }}">
{% endif %}
{% endfor %}

Beware of code indentation if your post is a markdown file, four space indentation can be transformed to code snippet.

Upvotes: 4

Related Questions