How to Use Jekyll Environments
If you read the previous article explaining Jekyll environments, you’re now ready to implement them.
In the last article, I wrote about how you may want to include Google Analytics tracking on your Jekyll website. The problem is we don’t want it running when testing the site locally on the development computer. In this article, we’re going to use environments in order to control when this feature is added to our site.
How Do You Use Jekyll Environments
Editing Layout
This code is pasted in the default layout file, so that the Google Analytics code is used on every post and page.
{%- if jekyll.environment == 'production' -%}
{%- include google-analytics.html -%}
{%- endif -%}
My Google Analytics code is stored in a file called google-analytics.html
,
and it is only included if the environment is production
.
Building the website
When building the project,
specify the environment you would like to use
by setting the JEKYLL_ENV
variable.
This can be accomplished with
JEKYLL_ENV=production jekyll build
or if using Bundler,
JEKYLL_ENV=production bundle exec jekyll build
Jekyll uses the following default environments.
JEKYLL_ENV=development
is set by default when building using thejekyll
(orbundle exec jekyll
) command from the terminal.development
is assumed if the variable is not set. Can be changed to any other value.JEKYLL_ENV=production
is set by GitHub Pages, when presenting the live site. That is, when you commit a jekyll project to GitHub, if the project is set up to use GitHub Pages, GitHub will build and render the site usingJEKYLL_ENV=production
. This function Cannot be changed on GitHub, can only be changed if building locally. But you can set up environments using any name and conditionals you like.
How Do I Check That My Jekyll Environment is Working
The easiest way is to serve your website, and check that the source code is what you expect.
But we may want a more visual representation of the environment. Another way is to print the environment with something like
<h2>Environment: {{ jekyll.environment }}</h2>
However, this can be a problem for your production website. You don’t want your users to see a huge heading that says “production” on the live site. So instead, this might be a more desirable code.
{% if jekyll.environment != "production" %}
<strong class=environment>{{jekyll.environment}}</strong>
{% endif %}
This way, the environment is printed on every environment except production. This is the approach we use on this website. The CSS is even set to flash this red and white, to make sure the developer is sure which environment they’re working on
Now that you know how to use Jekyll environments, and have some examples of when you might need them, you have everything you need to create your own environment conditionals.