Get asset path from javascript

After passing template directory URI to javascript with wp_localize_script, I can set up the assets path to give a marker to google map:

// assets/scripts/routes/example.js
var iconBase = sj.templateDirectoryUri + '/dist/images/';
icon: iconBase + 'sj-logo-marker.png',

This returns a path that seems right:

http://localhost:3000/wp/dist/images/sj-logo-marker.png 

But I get 404 in the console. Also, althoug this PNG is in its place:

46

it is not in the source inpector (there is no dist/images/ folder):

24

What is the right way to reference assets from JS?

The path should be something like: /app/themes/sj/dist/images/sj-logo-marker.png not /wp/dist/images/sj-logo-marker.png

1 Like

Thank you. After some years I have a little mess with paths and URIs in my head.

Reminder for me:

$sj_data = array(
   'homeUrl => get_bloginfo( 'url' ),
);

JS:

var iconBase = sj.homeUrl + '/app/themes/sj/dist/images/';

Not super necessary, but you can make that syntax a tad nicer with a template literal:

var iconBase = `${sj.homeUrl}/app/themes/sj/dist/images/`;
1 Like

Done! thanks for the advice.

Iā€™m trying to do the same thing here, could you please tell me where to insert the wp_localize_script and your $sj_data array?

Place it in setup.php amongst the standard wp_enqueue_script calls.

1 Like

Here you have it:

https://bitbucket.org/aitormendez/superbiajuridico/src/c6144a3e2281249c97ce9946fbbf0330a5f0a716/web/app/themes/sj/app/setup.php#lines-132:144

1 Like