Can't assign a string as JSON input in Pug file with Imigx parameters

107 views Asked by At

I have converted working HTML code into Pug that is using parameters from the Imgix.js library but the Pug version has an error. I have tried both methods (note the backticks on the ix-params):

img(ix-path="image.jpg", ix-params='{"w": 100}')
img(ix-path="image.jpg", ix-params={"w": 100})

But get an Uncaught SyntaxError: Unexpected end of JSON input console error. It appears that ix-params isn't allowing the assignment of a string as JSON input?

I can get it working by setting the ix-params as a variable, however this isn't viable for production.

- var ix_params = { "w": 100 }
img(ix-path="image.jpg", ix_params)
1

There are 1 answers

0
Graham On

According to the imgix docs you need to output something that looks like this:

<img
  ix-path="unsplash/hotairballoon.jpg"
  ix-params='{
    "w": 300,
    "h": 500,
    "fit": "crop",
    "crop": "right"
  }'
  alt="A hot air balloon on a sunny day"
>

The second way you tried to do this is what's causing the error, as pug expects a string or JavaScript expression after the equals sign and you're sending it a raw JSON object.

So let's try this out:

img(ix-path="unsplash/hotairballoon.jpg" ix-params='{"w": 300, "h": 500, "fit": "crop", "crop": "right"}' alt="A hot air balloon on a sunny day")

Produces this output which you clearly don't want:

<img ix-path="unsplash/hotairballoon.jpg" ix-params="{&quot;w&quot;: 300, &quot;h&quot;: 500, &quot;fit&quot;: &quot;crop&quot;, &quot;crop&quot;: &quot;right&quot;}" alt="A hot air balloon on a sunny day"/>

The way to get unescaped attributes is hidden near the bottom in the docs but you need to start that attribute with a bang/! and enclose the attribute with tildes ( ` ):

This pug statement:

img(ix-path="unsplash/hotairballoon.jpg" ix-params!= `{"w": 300, "h": 500, "fit": "crop", "crop": "right"}` alt="A hot air balloon on a sunny day")

Outputs this into the document which is close but not quite:

<img ix-path="unsplash/hotairballoon.jpg" ix-params="{"w": 300, "h": 500, "fit": "crop", "crop": "right"}" alt="A hot air balloon on a sunny day"/>

Switching the double and single quotes should work:

img(ix-path="unsplash/hotairballoon.jpg" ix-params!= "{'w': 300, 'h': 500, 'fit': 'crop', 'crop': 'right'}" alt="A hot air balloon on a sunny day")

Produces this:

<img ix-path="unsplash/hotairballoon.jpg" ix-params="{'w': 300, 'h': 500, 'fit': 'crop', 'crop': 'right'}" alt="A hot air balloon on a sunny day"/>

I'd personally rather have the single quotes on the outside and double quotes on the inside but can't figure out how to do that. Still, this should work as it's a valid JavaScript object.