Conditional javascript partials

I’m trying to make conditional javascript, so I can have a theme with features that that can turned on and off.

I tried putting the js file in partials and including it:

{{ if isset .Site.Params "coolfeature" }}
<script>
{{ partial "js/coolfeature.js" . }}
</script>
{{ end }}

…but the partial js file gets escaped like:

<script>
"$(function () {\n init();\n })\n"
</script>

How do I tell hugo to just include the js file without escaping it?

I found it works if I have surrounding my js, but then it’s not a js file and I don’t want multiple redundant tags. Ideally/ultimately I want to build a single js file.

Try putting the <script> tags in the partial or using something like this:

{{ partial "js/foo.js" . | safeJS }}

Go templates are very picky about context.

2 Likes

@moorereason perfect thanks, ‘| safeJS’ is exactly what I needed