From 80045f2f835dc17697d2be9c14f80697d36b2786 Mon Sep 17 00:00:00 2001 From: Jeremy Epstein Date: Mon, 22 Mar 2021 10:58:55 +1100 Subject: [PATCH] Pagination: bind `this` to `before` callback --- src/Plugins/Pagination.js | 2 +- test/PaginationTest.js | 14 ++++++++++++++ test/stubs/paged/paged-before-filter-this.njk | 14 ++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 test/stubs/paged/paged-before-filter-this.njk diff --git a/src/Plugins/Pagination.js b/src/Plugins/Pagination.js index 5815ffcc3..b55abbf23 100755 --- a/src/Plugins/Pagination.js +++ b/src/Plugins/Pagination.js @@ -126,7 +126,7 @@ class Pagination { typeof this.data.pagination.before === "function" ) { // we don’t need to make a copy of this because we already .filter() above - result = this.data.pagination.before(result); + result = this.data.pagination.before.bind(this)(result); } if (this.data.pagination.reverse === true) { diff --git a/test/PaginationTest.js b/test/PaginationTest.js index 8f165f6c9..0834e6c38 100644 --- a/test/PaginationTest.js +++ b/test/PaginationTest.js @@ -654,6 +654,20 @@ test("Pagination `before` Callback with a Filter", async (t) => { t.deepEqual(templates[0].data.myalias, "item2"); }); +test("Pagination `before` Callback with a Filter using `this` data", async (t) => { + let tmpl = getNewTemplate( + "./test/stubs/paged/paged-before-filter-this.njk", + "./test/stubs/", + "./dist" + ); + + let data = await tmpl.getData(); + let templates = await tmpl.getTemplates(data); + t.is(templates.length, 2); + t.deepEqual(templates[0].data.pagination.items, ["foo"]); + t.deepEqual(templates[1].data.pagination.items, ["woo"]); +}); + test("Pagination `before` Callback with `reverse: true` (test order of operations)", async (t) => { let tmpl = getNewTemplate( "./test/stubs/paged/paged-before-and-reverse.njk", diff --git a/test/stubs/paged/paged-before-filter-this.njk b/test/stubs/paged/paged-before-filter-this.njk new file mode 100644 index 000000000..de4eb6109 --- /dev/null +++ b/test/stubs/paged/paged-before-filter-this.njk @@ -0,0 +1,14 @@ +---js +{ + fooData: "moo", + pagination: { + data: "items", + size: 1, + before: function(data) { + return data.filter(item => item !== this.data.fooData); + } + }, + items: ["foo", "moo", "woo"] +} +--- +
    {% for item in pagination.items %}
  1. {{ item }}
  2. {% endfor %}
\ No newline at end of file