class Jekyll::AutoImageGenerator

Auto Image Generator

Sets {{page.image}} variable in liquid with the following fallback:

1) image value in front matter
2) first image in the post/pàge
3) _config.yaml image default
4) nothing (not set)

Public Instance Methods

generate(site) click to toggle source
# File lib/jekyll-auto-image.rb, line 44
def generate(site)
  @site = site

  site.pages.each do |page|
    img = get_image(page)
    page.data['image'] = img if img
  end
  # Now do the same with posts
  site.posts.docs.each do |post|
    #puts "hola"
    #puts Jekyll::VERSION
    #puts post.class
    #puts post.inspect
    #puts post.data.inspect
    #puts "-----"
    #puts post.output
    #puts "----"
    img = get_image(post)
    post.data['image'] = img if img
  end
end
get_image(page) click to toggle source

page: is either a Jekyll::Page or a Jekyll::Post in 2.x. In Jekyll 3.0 is Jekyll::Document and in Jekyll 3.3 is either Jekyll::Page or Jekyll::Document (fascinating!)

returns the path of the first image found in the contents of the page/post

# File lib/jekyll-auto-image.rb, line 73
def get_image(page)

  # debug lines
  #puts page.title
  #puts page.name
  #puts page.ext
  #puts @site.converters.select { |c| c.matches(page.ext) }.sort
  if page.data['image']
    return page.data['image']
  end

  # fix for jekyll 3.3.0,
  @site.config['kramdown'] = @site.config['kramdown'].dup

  # convert the contents to html, and extract the first <img src="" apearance
  # I know, it's not efficient, but rather easy to implement :)

  # Convertible for jekyll 3.0 and 3.3 posts & collections
  if page.class < Jekyll::Convertible || page.class == Jekyll::Document
    htmled = Jekyll::Renderer.new(@site, page, @site.site_payload).convert(page.content)
  else
    htmled = page.transform # for jekyll 2.x pages
  end

  img_url = htmled.match(/<img.*\ssrc=[\"\']([\S.]+)[\"\']/i)
  return img_url[1] if img_url != nil
  return @site.config['image'] if @site.config['image'] != nil
  return nil
end