Give your Eleventy Site Superpowers with Environment Variables
Eleventy is becoming increasingly popular with its simplicity and ease of use and powerful developer-friendliness. It is not only suitable for creating simple websites, but also capable of building large and complex projects. This tutorial will demonstrate how to build a powerful and easy-to-use solution with environment variables.
What are environment variables?
Environment variables are convenient variables/configuration values defined in the code run environment.
For example, a WordPress website may need to connect to different databases in production, test environments, and local environments. While these values can be hardcoded in wp-config.php
, a better approach is to keep the connection details private and facilitate code versioning (e.g. Git), i.e., to define these variables outside of the code.
Here is a standard WordPress wp-config.php
code snippet using hardcoded values:
<?php define( 'DB_NAME', 'my_cool_db' ); define( 'DB_USER', 'root' ); define( 'DB_PASSWORD', 'root' ); define( 'DB_HOST', 'localhost' );
Using tools such as phpdotenv
, you can modify the code to the following, and define variables outside the code:
<?php $dotenv = Dotenv\Dotenv::createImmutable(__DIR__); $dotenv->load(); define( 'DB_NAME', $_ENV['DB_NAME'] ); define( 'DB_USER', $_ENV['DB_USER'] ); define( 'DB_PASSWORD', $_ENV['DB_PASSWORD'] ); define( 'DB_HOST', $_ENV['DB_HOST'] );
One way to define the value of an environment variable is to use a .env
file, a text file that is usually ignored by version control .
These values can then be obtained using tools such as dotenv
or phpdotenv
, which may be inaccessible by default. Tools like dotenv
are very useful because these variables can be defined in .env
files, Docker scripts, or deployment scripts and they work fine - this is my favorite tool type!
These files are usually added to a version control ignore list (such as .gitignore
) because they usually contain keys or database connection information. Ideally, this information should be kept confidential and avoided adding it to a remote repository (such as GitHub).
Start operation
This tutorial provides some initial files to save time. This is a basic Eleventy website, with all the tedious steps done.
The first step is to download the initial file and decompress it anywhere. After decompression, open the folder in the terminal and run npm install
. When finished, run npm start
. Open http://localhost:8080
in your browser and you should see the following content:
Additionally, during the setup process, create a new empty file named .env
and add it to the root directory of the underlying file folder .
Create a friendly interface
Environment variables usually use all capital letters, which can be irritating. I'm more inclined to create a JavaScript interface to use these values and export them into a more understandable namespace form so that you can know that environment variables are used by just looking at the code.
For example, HELLO=hi there
may be defined in the .env
file. To access it, you can use process.env.HELLO
, but it becomes a bit boring after multiple calls. What if the value is not defined? It is very useful to provide a fallback value in this case. Using JavaScript settings, you can do the following:
require('dotenv').config(); module.exports = { hello: process.env.HELLO || 'Hello not set, but hi, anyway ?' };
This code looks for environment variables and sets the default value if necessary, using the OR operator (||) to return a value when undefined. Then, you can use {{ env.hello }}
in the template.
Now that we know the principles of this technology, let's implement it. In the initial file folder, there is a directory called src/_data
that contains an empty env.js
file. Open it and add the following code:
require('dotenv').config(); module.exports = { otherSiteUrl: process.env.OTHER_SITE_URL || 'https://eleventy-env-vars-private.netlify.app', hello: process.env.HELLO || 'Hello not set, but hi, anyway ?' };
Since the data file is named env.js
, it can be accessed in the template using the env
prefix. If you want the environment variable to be prefixed with environment
, you should rename the data file to environment.js
. For more information, please refer to the Eleventy documentation.
We set the hello
value and otherSiteUrl
value here, which is used to display different versions of the website according to the environment variable configuration. This setting uses the Eleventy JavaScript data file, allowing JavaScript to be run and the output is returned as static data. They even support asynchronous code! These JavaScript data files are probably my favorite Eleventy features.
Now that we have set up this JavaScript interface, let's go into the content and implement some variables. Open src/index.md
and add the following at the bottom of the file:
Here's an example: The environment variable, HELLO is currently: "{{ env.hello }}". This is called with {% raw %}{{ env.hello }}{% endraw %}.
Very cool, right? We can use these variables directly in the content in Eleventy! Now, when you define or change the value of HELLO
in the .env
file and restart npm start
task, you will see the content update.
Your website should now look like this:
You may be wondering what {% raw %}
is. It is a Nunjucks tag that allows you to define areas that it should ignore. Without it, Nunjucks will try to evaluate the {{ env.hello }}
section.
Modify the basic path of the picture
The first example is cool, but let's really start exploring what this approach is for. Usually, you want to use some kind of CDN to provide images in the production environment, but you may need to use local images when developing a website. This means that to improve performance and support different image formats, CDNs are often used to serve images, which usually serve images directly from websites (e.g. /images
folders). This is exactly what I do with ImgIX in Piccalilli, but these CDNs don't have access to the local version of the website. Therefore, it is very convenient to be able to switch between a CDN and a local picture.
This problem can be easily solved with environment variables – especially with Eleventy and dotenv
, because if the environment variable is not defined when used, no error is thrown.
Open src/_data/env.js
and add the following properties to the object:
imageBase: process.env.IMAGE_BASE || '/images/', imageProps: process.env.IMAGE_PROPS,
We use /images/
as the default value for imageBase
so that if IMAGE_BASE
is not defined, the local image can be found. We did not do the same with imageProps
because they can be empty unless needed.
Open _includes/base.njk
and add the following after <h1 id="title">{{ title }}</h1>
:
<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174344833541080.jpg" class="lazy" alt="Some lush mountains at sunset">
By default, this will load /images/mountains.jpg
. Very cool! Now, open the .env
file and add the following to it:
<code>IMAGE_BASE=https://assets.codepen.io/174183/ IMAGE_PROPS=?width=1275&height=805&format=auto&quality=70</code>
If you stop Eleventy (press Ctrl C in the terminal), then run npm start
again, and then view the source code in the browser, the rendered image should look like this:
<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174344833541080.jpg" class="lazy" alt="Some lush mountains at sunset">
This means that we can only take advantage of CodePen's resource optimization if needed.
Use Eleventy to provide private and advanced content
We can also use environment variables to render content conditionally based on schemas (such as private schemas). This is very important to me personally, as I have an Eleventy course and a CSS book, both powered by Eleventy and only paid users can see advanced content. There are a lot of technical magic behind the scenes, such as Service Workers and APIs, but the core is that the content can be rendered conditionally in our JavaScript interface based on env.mode
.
Let's add this to our example now. Open src/_data/env.js
and add the following to the object:
mode: process.env.MODE || 'public'
This setting means that by default, the mode is public . Now, open src/index.md
and add the following at the bottom of the file:
{% if env.mode === 'private' %} ## This is secret content that only shows if we're in private mode. This is called with {% raw %}`{{ env.mode }}`{% endraw %}. This is great for doing special private builds of the site for people that pay for content, for example. {% endif %}
If you refresh the local version, you will not be able to see what we just added. This works very well for us – especially as we want to protect it. So now let's use environment variables to display it. Open .env
and add the following to it:
<code>MODE=private</code>
Now, restart Eleventy and reload the website. Now you should see something like the following:
This conditional rendering can be run in a template. For example, you can set all page content to private and render a paywall. For example, if you visit my course without a license, you will see a call to action for purchase:
Fun mode
So far, these should be very useful for you, so let's expand on what we've learned and have fun with it!
Finally, I want to create a "fun pattern" that will completely change the design to a more...funny style. Open src/_includes/base.njk
and add the following before the end tag:
{% if env.funMode %} <link href="https://fonts.googleapis.com/css2?family=Lobster&display=swap" rel="stylesheet"> body { font-family: 'Comic Sans MS', cursive; background: #fc427b; color: #391129; } h1, .fun { font-family: 'Lobster'; } .fun { font-size: 2rem; max-width: 40rem; margin: 0 auto 3rem auto; background: #feb7cd; border: 2px dotted #fea47f; padding: 2rem; text-align: center; } {% endif %}
This snippet sees if our funMode
environment variable is true, and if so, add some "fun" CSS.
Still in base.njk
, add the following code before starting the tag:
{% if env.funMode %} <div> <p>? <strong>Fun mode enabled!</strong> ?</p> </div> {% endif %}
This code uses the same logic, rendering a fun banner if funMode
is true. Let's now create an environment variable interface for this. Open src/_data/env.js
and add the following to the exported object:
funMode: process.env.FUN_MODE
If funMode
is not defined, it will act as false because undefined
is a false value.
Next, open the .env
file and add the following to it:
<code>FUN_MODE=true</code>
Now, restart the Eleventy task and reload the browser. It should look like this:
Very cool, right? ! While this design looks bad (read: cool), I hope it demonstrates how many changes you can make with this environment settings.
Summarize
We created three versions of the same website, running the same code to see all the differences:
- Standard website
- Show private content
- Fun mode
All of these sites are powered by the same code, the only difference between each site is some environment variables, which in this case I defined in my Netlify dashboard.
I hope this technology will open up all possibilities for your work and use the best static website generator, Eleventy!
The above is the detailed content of Give your Eleventy Site Superpowers with Environment Variables. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference

Have you ever needed a countdown timer on a project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more

Everything you ever wanted to know about data attributes in HTML, CSS, and JavaScript.

When the number of elements is not fixed, how to select the first child element of the specified class name through CSS. When processing HTML structure, you often encounter different elements...

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

How to implement Windows-like in front-end development...

Tartan is a patterned cloth that’s typically associated with Scotland, particularly their fashionable kilts. On tartanify.com, we gathered over 5,000 tartan
