Web Island Agency

Custom Jekyll Filter for Linking Remote Assets

Custom Jekyll Filter for Linking Remote Assets
Custom Jekyll Filter for Linking Remote Assets

If you have a small static website and few images, storing assets on CDN may be overwhelming. In this case, the default solution for Jekyll is storing assets in the project repository. If you're planning to grow your project, I strongly recommend to set up external storage for serving static assets.

When the project gets larger, updating assets on production becomes more complex than updating files to CDN. It might be unsafe and lead to unexpected issues to connect the project to the same CDN for the development and production environment.

Setting up of CDN is not enough, also you need an effective way to build asset URLs depending on the build environment. The best practice for solving the type of task is utilizing a filter on the asset path string.

Jekyll utilizes Liquid as a default template engine. Liquid has various built-in filters for solving a wide range of tasks, but one of the best parts of Jekyll is that it provides API for creating custom filters.

Custom filters in Jekyll are written in plain Ruby and can be registered by putting the .rb files in the /_plugins folder.

Put the following snippet inside /_plugins/custom_filter.rb folder.

# Declare module of your plugin under Jekyll module
module Jekyll::CustomFilter

  # Each method of the module creates a custom Jekyll filter
  def asset_url(input)
    # asset_url filter business logic

    # Jekyll environment variable fallbacks to development
    env = ENV['JEKYLL_ENV'] || 'development'

    # Check if environment is development
    is_development = env == 'development'

    # Set host variable
    asset_host = is_development ? 'http://dev-bucket.s3-website-us-east-1.amazonaws.com' : 'http://prod-bucket.s3-website-us-east-1.amazonaws.com'

    # Return result URL string
    "#{asset_host}#{input}"
  end
end

Liquid::Template.register_filter(Jekyll::CustomFilter)

Now you can use your custom filter as follows:

'/img/logo.png' | asset_url

Join the discussion!

The article is published under the tags

Read more articles related to the topic