The Challenge: Using a config.yml Parameter in a JavaScript File

Lately, I found myself in a predicament.

I wanted to use a config.yml parameter in a JavaScript file, and apparently, it’s not that easy since most .js files are static as far as Hugo is concerned.

Why would you like to do that?

Well, let’s say you have a separate JavaScript file for Google Analytics that needs to be loaded at page start/end, but you don’t want to hardcode the Google Analytics ID.

The Solution Using js.Build

However, there is a way to do it using js.Build.

Technically, js.Build does more things, but it also does something interesting: it can map some parameters from the template file with the JavaScript file. For example, like this:

{{ $js := resources.Get "js/main.js" | js.Build (dict "params" (dict "api" "https://example.org/api")) }}

And in the JavaScript file then use:

import * as params from '@params';

Mapping Parameters with js.Build

Now, for us to be able to send parameters from Hugo config, then in the template file, we need to change (dict "api" "https://example.org/api") to (dict "GoogleAnalyticsId" $.Site.GoogleAnalytics).

For example:

{{ $js := resources.Get "/js/ga.js" | js.Build (dict "params" (dict "GoogleAnalyticsId" $.Site.GoogleAnalytics)) }}
<script type="text/javascript" src="{{ $js.RelPermalink }}"></script>

Make sure that ga.js is in the folder assets\js and not in static\js.

To use the params.GoogleAnalyticsId in ga.js, we need to do something like this:

import * as params from '@params';
console.log('Google Analytics Id : ',params.GoogleAnalyticsId);

// rest of the code that depends on params.GoogleAnalyticsId