Access template variables in JS

In my Hugo website, baseUrl is set to:website.com/variable.

If an image element is in .html (< img src="/images/image.png" >), the baseUrl is applied and the final url is this:website.com/variable/images/image.png/

If an image element is in .js (img.src = “/images/image.png”), the baseUrl is not applied and the final url is incorrect:website.com/images/image.png/

I tried to add a custom output format for js in config.toml, but it didn’t work:
[mediaTypes.“application/javascript”]
suffixes = [“js”]

Is there a way to access template variables in .js files?

No, I may be wrong, but from what I saw, Hugo does not phrase (apart of minification) javascript hence you cannot add for example {{ .Site.BaseURL }} into it unless you process your Javascript inside a shortcode or partial, then this may actually work.

1 Like

You can make use of “ExecuteAsTemplate”.

I do this in my Zen theme in a couple of places.

2 Likes

There is if you’re using Hugo Pipes to compile your script. You can add params to it which can later be invoked in the script.

basically you can call your script this way:

{{ $js := resources.Get "/js/indexjs" | js.Build (dict "params" (dict "baseurl" site.BaseURL")) }}

and then in your script:

import * as params from '@params';
console.log(params.baseurl)

More here

2 Likes

I saw this use of js.Build in another thread only a few days ago.

Will replace all my use of resources.ExecuteAsTemplate with js.Build for js files. It feels neater, allowing js files to be only javascript.

This feature have been around for nearly two years but I had missed it.

2 Likes