Eleventy(11ty) logo Eleventy
The possum is Eleventy’s mascot
Eleventy 中文文档
Menu
Eleventy 5.81s
Gatsby 43.36s

Quick Tip #011—Draft Posts using Computed Data

Here’s a quick snippet that shows how to combine Eleventy’s Configuration API Global Data and Computed Data features in your Eleventy Configuration file to implement a simple drafts feature for any piece of content.

Set draft: true anywhere in a file’s data cascade and that file will be only be built when using Eleventy in --serve or --watch modes. It will be excluded from full Eleventy builds.

You might imagine how this could be extended to add a publishing date feature too: to exclude content from builds before a specific date set in a post’s front matter (or elsewhere in the data cascade).

Filename .eleventy.js
module.exports = function(eleventyConfig) {
// When `permalink` is false, the file is not written to disk
eleventyConfig.addGlobalData("eleventyComputed.permalink", function() {
return (data) => {
// Always skip during non-watch/serve builds
if(data.draft && !process.env.BUILD_DRAFTS) {
return false;
}

return data.permalink;
}
});

// When `eleventyExcludeFromCollections` is true, the file is not included in any collections
eleventyConfig.addGlobalData("eleventyComputed.eleventyExcludeFromCollections", function() {
return (data) => {
// Always exclude from non-watch/serve builds
if(data.draft && !process.env.BUILD_DRAFTS) {
return true;
}

return data.eleventyExcludeFromCollections;
}
});

eleventyConfig.on("eleventy.before", ({runMode}) => {
// Set the environment variable
if(runMode === "serve" || runMode === "watch") {
process.env.BUILD_DRAFTS = true;
}
});
}