Jsonify in javascript context: unwanted escaping of quotes

I ran into the following issue when authoring a partial. I’m using:

{{ dict "a" 1 "b" 2 | jsonify }}

This results in


which is perfectly valid.

Now I want to use the same expression inside <script> tags:

<script onload='myfunc({{ dict "a" 1 "b" 2 | jsonify }});'</script>

This results in

<script onload='myfunc(&#34;{\&#34;a\&#34;:1,\&#34;b\&#34;:2}&#34;);'</script>

Notation &#34; is unwanted in this case, I want " instead. I don’t know how to achieve that, I tried with safeJS, to no avail.

Any help is appreciated here.

safeHTMLAttr to the help…


<script onload='myfunc({{ dict "a" 1 "b" 2 | jsonify | safeHTMLAttr }});'</script>

Same result, unfortunately. :frowning_face:

{{ $myFuncArgs := dict "a" 1 "b" 2 | jsonify }}
<script {{ printf "onload='%s'" (printf "myfunc(%s);" $myFuncArgs) | safeHTMLAttr }}></script>

safeHTMLAttr must be applied to the attribute name and value together, not just to the value.

@jmooring: Thanks for helping getting me started with hugo templating. Your code works like a charm and does exactly what its supposed to do.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.