Hugo

Aviod escaping in text out put

Hi there I’m getting error in json output string as Hugo is out putting escap characters with errors which are not necessary in json and also converting special characters into codes.

From screenshot You can see jsonlint isn’t validating it.
My actual text is “That’s some dummy text”.

[Detail] Actually I’m trying to output description of my post. I’m following this post. After getting everything done when I validated my ld+json using Google validator, google spotted an error which jsonlint also showing. I tried many things but no hope. Keep in mind that if edit text in jsonlint text box and write "description": "That's some dummy text." error goes away. That means error lies with escaping ' by \. Also note that escaping of quotation mark " is needed in every case.
Please any guide.
TY!

Meet your new best friend safeJS:

There are sibling functions for HTML, CSS, URLs, HTMLAttributes.

Use it like this:

{{ somethingthatwouldbeescaped | safeJS }}
1 Like

bro just explain me how. i’ve something like:

"description": "{{ if .Params.description }}{{ .Params.description }}{{ else }}{{ .Summary }}{{ end }}"
"description": "{{ if .Params.description }}{{ .Params.description | safeJS }}{{ else }}{{ .Summary | safeJS }}{{ end }}"

I tried that but not working. what I found from another old issue is that removing " like

  "description": {{ if .Params.description }}{{ .Params.description | safeJS }}{{ else }}{{ .Summary | safeJS }}{{ end }}

will remove this error but that also failed. because that’s output a naked text not a string.

congs! I’s just playing with some of other funtions and believe me htmlUnescape instead of safeJs worked very well. below is how my code looks now:

  "description": {{ if .Params.description }}{{ .Params.description | htmlUnescape }}{{ else }}{{ .Summary | htmlUnescape }}{{ end }}

Thanks btw.
Google structure data validator accepted it and it’s outputting pure string.

A change of direction.

My personal preference when building JSON with Hugo: create your data structure in code (using dict and slice and such) then convert it to JSON using the jsonify function. This avoids the to quote or not quote dance.

2 Likes