aelvan / Imager-Craft

This plugin has been DEPRECATED. Check out Imager X instead.
MIT License
342 stars 69 forks source link

Imgix urls have ampersands encoded, and shouldn't #276

Closed sam327 closed 5 years ago

sam327 commented 5 years ago

I'm on Craft 3.3.4.1, and Imager 2.2.0. And I've got it configured to use Imgix.

I'm using imager to insert variables into javascript. But when I do, the variables are coming out wrong.

So, simple version of my javascript, where I'm building an array (for a slideshow). Here's got two versions of an image, for responsiveness reasons.

{% set imageset = entry.images.all() %}
var images = [
    {% for image in imageset %} 
        {% set img2560 = craft.imager.transformImage(image, { width: 2560 }) %}
        {% set img1280 = craft.imager.transformImage(image, { width: 1280 }) %}
        [
            { width: 2560, url: "{{ img2560 }}" },
            { width: 1280, url: "{{ img1280 }}" }
        ]{% if not loop.last %},{% endif %}
    {% endfor %}
];

What's happening is that if my original image is here: https://dev.mysite.com/images/projects/testproject/firstProjectImage.jpg

the {{ img1280 }} variable is returning a url that looks like this: https://mysitedev.imgix.net/images/projects/testproject/firstProjectImage.jpg?auto=compress%2Cformat&convertToRGB=1&fit=max&w=1280 Which doesn't work right. It returns the original image.

What it should be showing is this: https://mysitedev.imgix.net/images/projects/testproject/firstProjectImage.jpg?auto=compress%2Cformat&convertToRGB=1&fit=max&w=1280 which returns a 1280px wide image.

I think I can fix it by changing my variables to {{ img1280 | raw }}

Also, this might be a craft bug rather than a imager bug. It feels like this just got bad when I ran the last updates, which got me to 3.3.4.1.

aelvan commented 5 years ago

So, Twig will escape whatever is output by default. Since this is a property on a model (you're outputting the url through the __tostring method when you just use the transform itself, but it's really img1280.url you're doing), it doesn't make sense to do anything in the model to output a raw string to twig. This would potentially break code that reads the URL inside the application, since the getUrl() method doesn't return a string any more, but a Twig object.

So yeah, this is the expected behaviour. The url breaks if you copy it and paste it into the browser, but it's valid for use in for instance an 's src or srcset attribute, it will decode correctly. If you use it in other instances, you might need to use the raw filter, or decode it manually.