Search code examples
imagemarkdownjekyllimage-gallery

Jekyll: Dealing with Images in Markdown


I've got a design for my post page that is made up of text and images, more specifically, galleries. Take a look at the illustration below:

enter image description here

I've got these galleries set up my front matter like so:

---
gallery-1:
  rows:
    - images:
      -  { url: '1.jpg'}
    - images:
      -  { url: '2.jpg'}
      -  { url: '3.jpg'}
gallery-2:
  rows:
    - images:
      -  { url: '4.jpg'}
      -  { url: '5.jpg'}
---

Is there a way to print these galleries to the page on my .md file. I know the code below won't work, but something similar?

This is my markdown

[gallery-1]

This is more markdown

[gallery-2]

Is something like this possible with Jekyll?

Any help with this is appreciated. Thanks in advance!


Solution

  • First, let's simplify your yaml front matter :

    ---
    galleries:
     # gallery number one
     1:
       # row one in gallery one
       -
         - { url: '1.jpg', alt: 'alt 1'}
       # row two in gallery one
       -
         - { url: '2.jpg', alt: 'alt 2'}
         - { url: '3.jpg', alt: 'alt 3'}
    
     # gallery number two
     2:
      # row one in gallery two
       -
         - { url: '4.jpg', alt: 'alt 4'}
         - { url: '5.jpg', alt: 'alt 5'}
    
    other front matter like title, ...
    ---
    

    Your .md file :

    Markdown
    {% include gallery.html  gallery=1 %}
    Other markdown
    {% include gallery.html  gallery=2 %}
    

    And then the _includes/gallery.html file :

    {% comment %}-----------------
      - This page receives a gallery index (include.gallery)
      - It then assign the gallery[include.gallery] to the rows variable
    %}-----------------{% endcomment %}
    {% assign rows = page.galleries[include.gallery] %}
    
    {% comment %}%}-----------------
      We now loop over rows
    %}-----------------{% endcomment %}
    {% for row in rows %}
    <div class="row">
        {% comment %}%}-----------------
          and then loop over images in row
        %}-----------------{% endcomment %}
        {% for img in row %}
            <p>src="{{ site.baseurl }}{{ img.url }}" alt="{{ img.alt }}"</p>
        {% endfor %}
    </div>
    {% endfor %}
    

    See yaml documentation And Jekyll template documentation