1
votes

I have an imgs subfolder in my _posts folder for jekyll. I link to images in that folder using the Markdown form:

![myimg](imgs/myimage.jpg)

When I generate the website, jekyll correctly creates the link:

<img src='imgs/myimage.jpg>

but it doesn't copy over the imgs folder with the image to the correct subdirectory in _site.

If the html is created as

_site/2013/10/myEntry.html

the image should be in the

_site/2013/10/imgs

folder for the link to work.

How can I configure jekyll to copy over the imgs folder to the correct place in the _site?

2
Just FYI -- the answer below will work fine, I think -- Jekyll only copies folders without preceding underscores, and only processes things in _posts with front matter. This is why it wasn't copying your images.tamouse
The plugin does work but thanks for the heads up about it only processing front matter. I'm sure I would have gone nuts figuring that out at some other point. ;)Dunfield

2 Answers

3
votes

While it is best to put your images folder at the root of your Jekyll site, you can make use of a plugin that will make Jekyll recognize your images folder inside _posts. Prefix your image files with the same date format as what you use for your posts and they'll be copied over to _site in the directory structure you want.

# _plugins/post_images.rb
module Jekyll
  POST_IMAGES_DIR = '_posts/imgs'
  DEST_IMAGES_DIR = 'imgs'

  class PostImageFile < StaticFile
    def destination(dest)
      name_bits = @name.split('-', 4)
      date_dir = ''
      date_dir += "#{name_bits.shift}/" if name_bits.first.to_i > 0
      date_dir += "#{name_bits.shift}/" if name_bits.first.to_i > 0
      date_dir += "#{name_bits.shift}/" if name_bits.first.to_i > 0
      File.join(dest, date_dir + DEST_IMAGES_DIR, name_bits.join('-'))
    end
  end

  class PostImagesGenerator < Generator
    def generate(site)
      # Check for the images directory inside the posts directory.
      return unless File.exists?(POST_IMAGES_DIR)

      post_images = []

      # Process each image.
      Dir.foreach(POST_IMAGES_DIR) do |entry|
        if entry != '.' && entry != '..'
          site.static_files << PostImageFile.new(site, site.source, POST_IMAGES_DIR, entry)
          post_images << entry.gsub(File.extname(entry), '')
        end
      end

      # Remove images considered to be "actual" posts from the posts array.
      site.posts.each do |post|
        if post_images.include?(post.id[1..-1].gsub('/', '-'))
          site.posts.delete(post)
        end
      end
    end
  end
end
0
votes

I have developed a Jekyll plugin that helps keep posts assets alongside the Markdown file, it might fill your needs: https://nhoizey.github.io/jekyll_post_files/