How do I set up a conditional config with Jekyll?

I found that there are a few ways of getting your Jekyll environment to behave differently for development purposes. I would use the first method if I’m going to conditionally change a thing or two in my templates but if I needed to change any of the variables in my config file, I would say the second one has much more functionality.


Method 1

This first example utilizes the Environment setting from the Jekyll documentation.

When you start your local server you can specify your JEKYLL_ENV as development and serve your site as usual.

  JEKYLL_ENV=development jekyll serve

Github pages will automatically set the production environment for you, but if you need to start your local dev in production after you’ve set development, you can then overwrite the environment variable.

  JEKYLL_ENV=development jekyll serve

You can use environment variables to do some convenient things like, conditionally load Google Analytics.

{% if jekyll.environment == "production" %}
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-12642425-1', 'auto');
  ga('send', 'pageview');

</script>
{% endif %}




Method 2

This method uses the Configuration setting from the Jekyll documentation. It gives you the ability to customize a whole config file as opposed to just using conditionals in liquid templates.

You probably already have a _config.yml, if not, go ahead and create one with a param called environment and set it to production.

environment: production

Create another configuration and name it whatever you like, for this example I’ll call it _config_dev.yml.

environment: development

When you fire up your server, overwrite your prod env with the dev one, so you’ll want to run a command that looks like this:

jekyll serve --config _config.yml,_config_dev.yml

This method is useful if you want to change site variables that are specified in your config (like a test account number or paths to your assets). You can also use your new config variables to conditionally include code:

{% if site.environment == "dev" %}
  <script>console.log("hey yah")</script>
{% endif %}
{% if site.environment == "production" %}
  <script>console.log("hey nah")</script>
{% endif %}


For more information take a look at the Jekyll documentation: https://jekyllrb.com/docs/configuration/

Back to Blog