Dynamically setting an image source


#1

I’m trying to generate an image source url dynamically based on the value of a repeater, like the following:

<template repeat.for="thing of things">
    <img src="../../../static/icons/${thing}.png">
  </template>

but the webpack CLI gives me the following error:

Module not found: Error: Can’t resolve ‘…/…/…/static/icons/${thing}.png’ in ‘C:\my project directory…’

Is there a different way I ought to be templating an element attribute?


#2

The easiest way is to have your static assets in static folder and copy them over with webpack copy plugin. Can you try that?


#3

So say that ${thing}.png resolves to picture.png, it’s not that webpack can’t find picture.png, it’s that webpack seems to be looking for a file literally called ${thing}.png.

${thing} doesn’t seem to be getting resolved into a string. However, if I put ${thing} between p tags, then it does correctly get rendered into the proper string. So for some reason it’s resolving when it’s text, but not when it’s in an element’s attribute.


#4

Does if work if you try?

src.bind="'../../../static/icons/' + thing + '.png'"

#5

I’m going to be running into an issue where I’ll be serving the images up from a server. How would webpack handle that? Imagine an image viewer with 100s of images and they live in a database.


#6

I’ve never really stored images directly in a database, if that’s what you mean? I’ve always stored details of the image and the path to where it’s stored on the file system - I’ve always found it more flexible. If you are storing the base64 encoded image data in a database, could you just add it to the img src like:

<img src.bind="'data:image/gif;base64,' + data" /> 

#7

There is definitely flexibility in storing images on the filesystem which is what my project currently does, but we are building a completely distributed system so with that, storing in the db (Mongo) makes it easier for us. I’ll have to try what you posted, that may work without webpack complaining


#8

The easiest would be to setup html-loader to ignore images processing. Then it will leave src tags alone.


#9

You could use a value converter,

<img src.bind="thing | convertThingtoUrl"><img>

Then create a simple value converter to add the …/…/…/static/icons/ and the .png


#10

I’m just using:

 <img src="${aircraftIcon}">

and setting the property in the activate lifecycle for the page:

this.aircraftIcon = 'img/' + this.selectedRegistration + '-Icon256.png'

Part of that is static and could be part of the src text, but I decided to keep it all together in one spot.


#11

Should be a one time bind
<img src="${aircraftIcon & oneTime}">
or on your property
@computedFrom(‘selectedRegistration’) -> scans for changes on that value


#12

Good point, thanks!
I don’t have many items that are being checked, but could make a difference for someone (me later when I do have more items ;))