Img source is a variable, the URL gets encoded

85 Views Asked by At

I have a multi-level hash in which I have a user's avatar's URL.

I am trying to make a cell with "Jane Doe image" but when the code runs the URL is getting changed. When I interpolate it into an Embperl template,

https://foo.com/useravatar?size=small&id=11111

turns into

https://foo.com/useravatar%3Fsize%3Dsmall%26id%3D11111

As you can see, the special characters become encoded and so the image is not found. How do you get around this?

use strict;
use warnings;

use Embperl qw( );

our $issue = {
   avatar => {
      url => 'https://foo.com/useravatar?size=small&id=11111',
   },
};

my $template = <<'__EOI__';
[+ $issue->{avatar}{url} +]
<img src="[+ $issue->{avatar}{url} +]">
__EOI__

Embperl::Execute({
   input   => \$template,
   package => __PACKAGE__,
});

This produces:

https://foo.com/useravatar?size=small&amp;id=11111
<img src="https://foo.com/useravatar%3Fsize%3Dsmall%26id%3D11111">

When the URL is inserted outside of the src attribute, it's correctly escaped. But when it's inserted inside of the src attribute, it gets mangled.

1

There are 1 best solutions below

4
On

The escaping you noticed is designed to handle

<img src="https://foo.com/useravatar?size=small&amp;id=[+ $avatar_id +]">

You can change the escaping mode. Use

<img src="[+ do { local $escmode = 1; $issue->{avatar}{url} } +]">

to produce

<img src="https://foo.com/useravatar?size=small&amp;id=11111">

to fetch the image at URL

https://foo.com/useravatar?size=small&id=11111

Test:

use strict;
use warnings;

use Embperl qw( );

our $issue = {
   avatar => {
      url => 'https://foo.com/useravatar?size=small&id=11111',
   },
};

my $template = <<'__EOI__';
<img src="[+ $issue->{avatar}{url} +]">
<img src="[+ do { local $escmode = 1; $issue->{avatar}{url} } +]">
__EOI__

Embperl::Execute({
   input   => \$template,
   package => __PACKAGE__,
});