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:


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


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


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' ),


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:

1 Like