How to pass in JSON encoded CSS data into Mustache template?

805 views Asked by At

So, we have some basic Mustache markup that is supposed to render JSON-encoded CSS classes in {{{override_css}}}.

....
<div class="js-modal-additional hidden-el"
  data-reposition="0"
  data-css="{{{override_css}}}">
</div>
....

And here's how we render our mustache object:

<?php
   ...
   $data->override_css =
   json_encode(
          array(
            'position' => 'fixed',
            'z-index' => 10,
            'top' => 'auto'
          )
   );

   ...
?>

Which unfortunately becomes:

<div class="js-modal-additional hidden-node" data-reposition="0" data-css="{" position":"fixed","z-index":3,"top":"auto"}">
</div>

I'm sorry if this has been covered before, but maybe I'm missing something? I'm surprisingly having a lot of difficulty passing in valid JSON. I thought of using preg_replace or some other hacky methods, but then it wouldn't be valid JSON now, would it? I need JS to be able to read and apply the CSS from data-css after in order to override the default. Anything to avoid !important tags. Call it bad design, but my hand is sort of forced here.

Any help is greatly appreciated though!

1

There are 1 answers

0
nzn On

Your JSON quotes are closing your data-css quotes after the first "{".

You need to HTML-escape your quotes. In your PHP code write:

<?php
   ...
   $data->override_css =
   htmlspecialchars(json_encode(
          array(
            'position' => 'fixed',
            'z-index' => 10,
            'top' => 'auto'
          )
   ));

   ...
?>

and it will work.