Inserting "Templates Variables" in Javascript

Hello !

I’d love to be able to add a button to display the disqus commentaries.
This way, the user can choose if he wants to display the commentaries or not.

One solution I found is to add a button which execute a javascript function. In this function, I want to add:
{{ template "_internal/disqus.html" . }}

But the problem is that I found no way to do that … Inserting html in this javascript doesn’t work either …

Do you see a way to add my variable in the javascript or to use another solution that this javascript ?

Thank you :slightly_smiling:

So nobody has a solution to my problem ? :confused:

If you want to add variables in Javacsript you will have to inline the Javascript in the template file.

Hi there,
I tried to use var langUser = '{{ .Site.languageUser := "en" }}';
in an html (template) file, and it’s not working.
Would you have any idea ?

Here is the error: error calling partial: Partial “js.html” not found

That is not the way to set a variable in Hugo. See the Docs.

Also the missing partial error is irrelevant to the variable.

That message means that Hugo is looking for /layouts/partials/js.html and it cannot find it. Somewhere in your templates there is a call for this partial and apparently it’s missing.

I know this is an old thread, but in modern hugo version, it is quite easy to do it. And as it took me some time to find the solution even with the forum, hope this helps others.

  • put your javascript with the needed {{ $variables }} in assets/js for example
  • call it as a template in your HTML partial/code.
{{ $path := "js/my_template.js" }}
{{ $js := resources.Get $path | resources.ExecuteAsTemplate $path . | minify }}
<script>{{ $js.Content | safeJS }}</script>

Yes, and this can be very useful for Javascript localization, if you need language specific strings in your javascript. An real-world example: