Solved – Using jsonify or queryify inside an HTML attribute

I’m having trouble passing a jsonify or a querify string into an HTML element.

I have tried the various safe techniques like safeHTML, safeURL, etc.

When using this:

{{ $.Scratch.Set "fluid" (jsonify(dict "mark" $mark "markw" 0.2 "markpad" 20)) }}

I can produce a beautiful JSON string. However, when put into an HTML object it produces an escaped JSON string.

Additionally, when trying querify, I get an HTML encoded URL.

{{ $.Scratch.Set "fluid" (querify "mark" $mark "markw" 0.2 "markpad" 20 ) }}

mark=https%3A%2F%2Fupsco.imgix.net%2Fupsco%2Fys%2Fimages%2Fbracket%2Fmarch-madness-bracket-logo-2014.png&markpad=20&markw=0.2

The purpose is that I use IMGIX for handling images and use JSON or query strings to pass extra parameters to the photos in an HTML attribute that is then handled in Javascript.

Any tips on passing values that do not get encoded?

It is not clear what you use to output your “fluid” but have you tried creating your map with .Scratch.SetInMap and then use {{ jsonify (.Scratch.Get "fluid") }}?

I can get the values clearly. But for example using jsonify

Using the following code…

{{ $.Scratch.Set "fluid" (jsonify (dict "mark" $mark "markw" 0.2 "markpad" 20 )) }}

{{ $.Scratch.Get "fluid" }}

<div data-fluid="{{ $.Scratch.Get "fluid" }}"></div> 

I get the following output.

 {"mark":"https://upsco.imgix.net/upsco/ys/images/bracket/march-madness-bracket-logo-2013.png","markpad":20,"markw":0.2}

<div data-fluid='{&#34;mark&#34;:&#34;https://upsco.imgix.net/upsco/ys/images/bracket/march-madness-bracket-logo-2015.png&#34;,&#34;markpad&#34;:20,&#34;markw&#34;:0.2}'></div>

The first is beautiful, but when put inside an HTML element it gets bungled. I’ve tried safeURL, safeHTML, and the others but still can’t achieve a non-decoded output.

I was not able to make it work… @kaushalmodi I wonder if this is this something you have already encountered?

How about:

{{ $.Scratch.Set "fluid" ((dict "mark" "foo" "markw" 0.2 "markpad" 20 ) | jsonify) }}
{{ printf "<div data-fluid='%s'></div>" ($.Scratch.Get "fluid") | safeHTML }}

HTML output:

<div data-fluid='{"mark":"foo","markpad":20,"markw":0.2}'></div>
2 Likes

Brilliant! This solves it, makes total sense, just didn’t think about approaching it this.

Thanks for the help.

Do you even need to use Scratch here? It seems the data is used in the same scope so it could just be stored in a local context variable, couldn’t it? :slight_smile:

1 Like

You’re right :). I didn’t give much thought to that. I assumed that the OP must have genuinely needed it and the snippet here was probably a part of a bigger picture.

1 Like