Hugo

How set parameter from JavaScript

How can I set a variable in Hugo based on JavaScript code?

Here is the situation. I have a template that turns dark mode on and off using JavaScript code that works by both adding a CSS class to the body element and also setting a variable in local JavaScript storage. On one of my pages, I embed a Twitter timeline widget. The widget can use a dark mode if it is given a parameter. I can pass it the parameter, but to do so, I need to write Hugo code that will detect if either the body element of the page has a certain class, or the local storage variable is set. In other words, I need to do something like {{ .Get [value from javascript] }}.

I can write necessary jQuery code to set the variable or check the body element for the class; what I can’t figure out is how connect the results of that to Hugo, either by setting a variable or taking some other action that will allow me to write a conditional in a Hugo template.

My apologies if this has been asked or is explained somewhere. I’m happy to RTFM if someone can point me to the right FM to R :-).

What you’re asking is not trivial at all.

The way to set Hugo variables via JS can be done only for inlined JS that is contained within a proper Hugo template.

There is a theme that I have come across that uses more or less what you describe to set a dark mode and it is this one:

Have a look at its repo.

I don’t think this is possible, at least in the way you describe. Once your site is generated by hugo, then hugo is “out of the picture”. In other words, you can set a JavaScript variable with hugo, but not the other way around.

Thank you for the replies. Some further work has led me to understand why what I asked for won’t work (namely, the reason @zwbetz describes). I’ve temporarily given up on a solution and worked around what I was trying to do, and will take a look at the repo mentioned by @onedrawingperday for additional ideas.