diff --git a/src/ext/path-params.js b/src/ext/path-params.js new file mode 100644 index 000000000..e251b8927 --- /dev/null +++ b/src/ext/path-params.js @@ -0,0 +1,11 @@ +htmx.defineExtension('path-params', { + onEvent: function(name, evt) { + if (name === "htmx:configRequest") { + evt.detail.path = evt.detail.path.replace(/{([^}]+)}/g, function (_, param) { + var val = evt.detail.parameters[param]; + delete evt.detail.parameters[param]; + return val === undefined ? "{" + param + "}" : encodeURIComponent(val); + }) + } + } +}); \ No newline at end of file diff --git a/test/ext/path-params.js b/test/ext/path-params.js new file mode 100644 index 000000000..3f0ac3a3c --- /dev/null +++ b/test/ext/path-params.js @@ -0,0 +1,51 @@ +describe("path-params extension", function() { + beforeEach(function () { + this.server = makeServer(); + clearWorkArea(); + }); + afterEach(function () { + this.server.restore(); + clearWorkArea(); + }); + + it('uses parameter to populate path variable', function () { + var request; + htmx.on("htmx:beforeRequest", function (evt) { + request = evt; + }); + var div = make("
") + div.click(); + should.equal(request.detail.requestConfig.path, '/items/42'); + }); + + it('parameter is removed when used', function () { + var request; + htmx.on("htmx:beforeRequest", function (evt) { + request = evt; + }); + var div = make("") + div.click(); + should.equal(request.detail.requestConfig.parameters.other, 43); + should.equal(request.detail.requestConfig.parameters.itemId, undefined); + }); + + it('parameter value is encoded', function () { + var request; + htmx.on("htmx:beforeRequest", function (evt) { + request = evt; + }); + var div = make("") + div.click(); + should.equal(request.detail.requestConfig.path, '/items/a%2Fb'); + }); + + it('missing variables are ignored', function () { + var request; + htmx.on("htmx:beforeRequest", function (evt) { + request = evt; + }); + var div = make("") + div.click(); + should.equal(request.detail.requestConfig.path, '/items/42/{subitem}'); + }); +}); diff --git a/test/index.html b/test/index.html index eb6f15b18..88b113150 100644 --- a/test/index.html +++ b/test/index.html @@ -161,6 +161,9 @@