0

I'm using the rewrite option of a view field to generate some HTML. One tag has a data attribute, which should contain an array for later use in JavaScript with JSON.parse():

<div data-image-src='["{{ field_parallax_background_image }}"]'>…</div>

For JSON.parse() it is necessary to enclose the array fields within double quotes, therefore I have to use single quotes for the enclosure of the HTML attribute. The output should look as follows:

<div data-image-src='["/sites/default/xyz.jpg", "/sites/default/xyz.jpg", "…"]'>…</div>

But somewhere in the process Drupal replaces the singe quotes with double quotes, changing the output to:

<div data-image-src="["/sites/default/xyz.jpg", "/sites/default/xyz.jpg", "…"]">…</div>

Which apparently is misformatted.

My question is, why does this happen, where does it happen, and is there a clean workaround?

I know, that it would be a much cleaner approach to write a custom views field. But then again, this feels a bit like an overkill.

  • I'm not sure if you can change AttributeValueBase::render() behavior. Is an a JSON object without key/value even valid anyway? I think you would want an array of values (same issue though). You'll probably need to add the data attribute via javascript behaviors yourself. – mradcliffe Dec 10 '18 at 3:12
  • @mradcliffe Yes, it works without key/value, but one has to use square brackets instead of curly brackets, then you get an array instead of an object, as far as I know. I corrected the example accordingly. Shouldn't AttributeValueBase::render() check whether $value contains double quotes, and in this case use single quotes for enclosure? – user5950 Dec 10 '18 at 10:17
  • 1
    Have you tried replacing " with &quot;? I've not tested this with views, but it worked for me when passing JSON into a data attribute in a Twig file. – Hudri Dec 10 '18 at 10:34
  • @Hudri This works in the sense of that &quot; gets decoded correctly but in the case above you would still get nested double quotes, ergo invalid HTML. – user5950 Dec 10 '18 at 11:33
  • 1
    I've expected an output like <tag attribute="{&quot; key &quot; : &quot; value &quot;}">, which is valid HTML. Be sure to check the real source, not just DevTools of the browser. – Hudri Dec 10 '18 at 12:13

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.