From b0efad7ac924638f71f22bdf3e0f70ad568db598 Mon Sep 17 00:00:00 2001 From: Fabien O'Carroll Date: Mon, 29 Jul 2019 16:54:09 +0800 Subject: [PATCH] =?UTF-8?q?Fixed=20img=5Furl=20helper=20when=20using=20ima?= =?UTF-8?q?ge=20sizes=20with=20relative=20path=E2=80=A6=20(#10964)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit closes #10949 This updates the getImageWithSize function in the img_url helper to consider relative paths WITHOUT a leading slash the "base case". If a path does have a leading slash, we remove it, pass it through the function again, and then prepend the slash. --- core/frontend/helpers/img_url.js | 8 +++++++- core/test/unit/helpers/img_url_spec.js | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/core/frontend/helpers/img_url.js b/core/frontend/helpers/img_url.js index d5156c555d..f0cf8c055b 100644 --- a/core/frontend/helpers/img_url.js +++ b/core/frontend/helpers/img_url.js @@ -11,7 +11,7 @@ const url = require('url'); const _ = require('lodash'); const proxy = require('./proxy'); const urlUtils = proxy.urlUtils; -const STATIC_IMAGE_URL_PREFIX = `/${urlUtils.STATIC_IMAGE_URL_PREFIX}`; +const STATIC_IMAGE_URL_PREFIX = `${urlUtils.STATIC_IMAGE_URL_PREFIX}`; module.exports = function imgUrl(requestedImageUrl, options) { // CASE: if no url is passed, e.g. `{{img_url}}` we show a warning @@ -94,6 +94,12 @@ function detectInternalImage(requestedImageUrl) { } function getImageWithSize(imagePath, requestedSize, imageSizes) { + const hasLeadingSlash = imagePath[0] === '/'; + + if (hasLeadingSlash) { + return '/' + getImageWithSize(imagePath.slice(1), requestedSize, imageSizes); + } + if (!requestedSize) { return imagePath; } diff --git a/core/test/unit/helpers/img_url_spec.js b/core/test/unit/helpers/img_url_spec.js index 41114529c5..0913c4c2ef 100644 --- a/core/test/unit/helpers/img_url_spec.js +++ b/core/test/unit/helpers/img_url_spec.js @@ -179,5 +179,24 @@ describe('{{image}} helper', function () { should.exist(rendered); rendered.should.equal('/content/images/size/w400/my-coole-img.jpg'); }); + + it('should output the correct url for relative paths without leading slash', function () { + var rendered = helpers.img_url('content/images/my-coole-img.jpg', { + hash: { + size: 'medium' + }, + data: { + config: { + image_sizes: { + medium: { + width: 400 + } + } + } + } + }); + should.exist(rendered); + rendered.should.equal('content/images/size/w400/my-coole-img.jpg'); + }); }); });