Sam Houston
Sam Houston

Reputation: 3651

Reference the correct static file in phoenix

In a phoenix project, I can reference digested img in a css file with:

background-image: url("/images/phoenix.png");

and that references:

http://localhost:4000/images/phoenix-5bd99a0d17dd41bc9d9bf6840abcc089.png?vsn=d

I would like to reference the same file, but the image src added with javascript, like so:

document.querySelector('#my-img').src = '/images/phoenix.png';

But this only references:

http://localhost:4000/images/phoenix.png

How can I configure the phoenix endpoint to instead serve the digested img file?

(I would like this functionality for updating cached file purposes)

Upvotes: 4

Views: 1065

Answers (1)

Badu
Badu

Reputation: 1082

Since you know the image file beforehand, you can have a javascript variable and set the value to the URL to that image file and use it later in your script

Something like this in your .eex template:

<script>
 // using static_path(@conn, "/path/to/asset") will give the digested file url
 var disgestedImageUrl ="<%= static_path(@conn, "/images/phoenix.png") %>";
</script>

Then have your script that uses the URL in your .js file

<script>
  document.querySelector('#my-img').src = digesterImageUrl;
</script>

Upvotes: 1

Related Questions