0

I'm facing a weird challenge where I need to include a static resource image inside an aura:iteration loop.

The challenge here is this:

<img src="{!$Resource.testbox}"/>

This will display the image in the lightning component fine.

But if you want different images to be displayed based on a List you're running through aura:iteration the challenge begins. How do I structure the src to use the variable to set the static resource name? (the dt.img variable contains 'testbox', I have triple checked)

<aura:iteration items="{!v.extraDecoderTypes}" var="dt" indexVar="idx">
<img src="{!$Resource + dt.img}"/>
</aura:iteration>

In my head this should work fine, but it does not. So I guess the problem is that $Resource should be $Resource. (with "."). But if I do that in the code, I will get this error:

expecting an identifier, found '+' at column 12 of expression: $Resource. + dt.img

Trying without the "." will get uploaded to org, but the image will not display.

https://developer.salesforce.com/docs/atlas.en-us.234.0.lightning.meta/lightning/expr_resource_value_provider.htm does not mention this exact case, but more how to get resource that are below one level in the directory structure.

Any tips would be greatly appreciated!

2
  • The $Resource.name does not work that way since the path varies with upload timestamps for different static resources. You need the specific full references or you need to put all your static resources into a ZIP static resource. See the documentation.
    – Phil W
    Oct 16, 2022 at 20:32
  • @PhilW The timestamp parameter is optional.
    – sfdcfox
    Oct 16, 2022 at 21:35

1 Answer 1

0

To get a dynamic value, you have to use $A.get, as in:

const resourceUrl = $A.get('$Resource.'+dt.img);

This is done in the JavaScript controller, which you then place the result thereof into an attribute, such as:

const extraDecoderTypes = data.map(
  (record) => 
    Object.assign({}, record, { resourceUrl: $A.get('$Resource.'+record.img) })
);

This was the part of the documentation you missed where they wrote:

var profUrl = $A.get('$Resource.yourGraphics') + '/images/avatar1.jpg';

Even though they show getting a path, notice how the first parameter is a string; you can use that to create a resource URL dynamically, since it's just string concatenation.

1
  • Thanks sfdcfox! This solved this issue for me! I added this to the Javascript-controller object: component.set('v.extraDecoderTypes', [ {id: 0, type: 'Telia BoX', hwid: 1715, label: 'Ekstra Telia BoX', img: $A.get('$Resource.'+ 'teliabox'), amount: 0} ]); and it works like a charm!
    – Firestone
    Oct 17, 2022 at 7:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .