Excluding Posts by Environment

Header image for Excluding Posts by Environment

Publish posts depending on your build environment.

2 minute reading time of 406 words (inc code) Code available at codeberg.org and the last commit was

I’ve got a to-do list for this site, and it made sense to keep it as part of the site - after all, it’s just a normal itemised list with things that get struckthrough as I check them off, and keeping it on the site may make me remember where it is and to look at it once in a while.

But I only want to publish it to my development instance; it’s not a post I want to publish to the whole world, or you’ll all see how many items are left…

Enter this little plugin snippet:

require "jekyll"

module EnvironmentExcludePosts

  @@environment = ENV["JEKYLL_ENV"]
  
  def self.process(site)
    
    # check we've got anything to compare this build environment against
    if @@environment.nil? or @@environment.empty?
      Jekyll.logger.warn "EnvironmentExcludePosts: Environment variable not set - expecting JEKYLL_ENV to be set for the build."
      return
    end
    
    # loop through all the posts
    site.posts.docs.each_with_index do |post, index|
      
      # and if we match
      if post.data.key?("environment") and post.data["environment"] != @@environment
      
        # remove it from Jekyll's "to be rendered" list - this will also stop any
        # associated files (like images if you keep them alongside) from being made
        site.posts.docs.delete_at(index)
        
        Jekyll.logger.info "EnvironmentExcludePosts: Post excluded from #{@@environment} build (#{post.data['title']} = #{post.data['environment']})"
      end
    
    end
    
  end
  
end

# add a hook that's run before we start processing the site
Jekyll::Hooks.register :site, :post_read do |site|
  EnvironmentExcludePosts.process(site)
end

And to make use of it, just add the environment: whatever variable to the relevant posts’ front matter, and set the server’s environment variable before calling your build - eg. like JEKYLL_ENV=production /usr/bin/bundle exec jekyll build.


Reply via email