Skip to content

Commit

Permalink
Fixes #2179
Browse files Browse the repository at this point in the history
  • Loading branch information
zachleat committed Jan 18, 2022
1 parent 08fe54e commit 900eec4
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/TemplateData.js
Expand Up @@ -294,6 +294,8 @@ class TemplateData {

async getInitialGlobalData() {
let globalData = {};

// via eleventyConfig.addGlobalData
if (this.config.globalData) {
let keys = Object.keys(this.config.globalData);
for (let key of keys) {
Expand All @@ -306,6 +308,7 @@ class TemplateData {
lodashset(globalData, key, returnValue);
}
}

if (this.environmentVariables) {
if (!("eleventy" in globalData)) {
globalData.eleventy = {};
Expand All @@ -315,15 +318,16 @@ class TemplateData {
}
Object.assign(globalData.eleventy.env, this.environmentVariables);
}

return globalData;
}

async getData() {
let rawImports = this.getRawImports();

this.configApiGlobalData = await this.getInitialGlobalData();

if (!this.globalData) {
this.configApiGlobalData = await this.getInitialGlobalData();

let globalJson = await this.getAllGlobalData();
let mergedGlobalData = merge(globalJson, this.configApiGlobalData);

Expand Down
15 changes: 15 additions & 0 deletions test/EleventyTest.js
Expand Up @@ -369,3 +369,18 @@ test("Can Eleventy run two executeBuilds in parallel?", async (t) => {
test2Result
);
});

test("Eleventy addGlobalData should run once.", async (t) => {
let count = 0;
let elev = new Eleventy("./test/stubs", "./test/stubs/_site", {
config: function (eleventyConfig) {
eleventyConfig.addGlobalData("count", () => {
count++;
return count;
});
},
});

let results = await elev.toJSON();
t.is(count, 1);
});
18 changes: 18 additions & 0 deletions test/TemplateDataTest.js
Expand Up @@ -486,6 +486,24 @@ test("addGlobalData values", async (t) => {
t.is(data.myAsync, "promise-value");
});

test("addGlobalData should execute once.", async (t) => {
let count = 0;
let eleventyConfig = new TemplateConfig();
eleventyConfig.userConfig.addGlobalData("count", () => {
count++;
return count;
});

let dataObj = new TemplateData(
"./test/stubs-global-data-config-api/",
eleventyConfig
);
let data = await dataObj.getData();

t.is(data.count, 1);
t.is(count, 1);
});

test("addGlobalData complex key", async (t) => {
let eleventyConfig = new TemplateConfig();
eleventyConfig.userConfig.addGlobalData("deep.nested.one", () => "first");
Expand Down

0 comments on commit 900eec4

Please sign in to comment.