-
-
Save danschumann/ae0b5bdcf2e1cd1f4b61 to your computer and use it in GitHub Desktop.
myObject = { ... } | |
this.injectString = JSON.stringify( myObject ).replace(/\\/g, '\\\\').replace(/"/g, '\\\"') |
We only worry about parsing now, since everything should have been properly escaped | |
<script> | |
window.myObjectFrontend = JSON.parse("<%- @injectString %>"); | |
</script> |
We replace \
with \\
and "
with \"
so that it can be 1 string when it is printed in html
We are replacing because it needs to be passed to frontend through JSON.parse("{{injectString}}");
( note the "
wrapping the backend string ).
"{"mykey":"my\"val"}"
-- pre-regex -- not parseable, the frontend sees this as 4 strings with junk in between
"{\"mykey\":\"my\\\"val\"}"
-- post-regex -- parseable
the first replace is for my\"val
, since the second replace would cause that to break. If only the second replace was applied, it would become my\\"val
means it escapes a slash, and the double quotes would end the parse string prematurely. Applying both regexes makes it my\\\"val
, the first two slashes make one slash, and the third escapes the "
, making it identical to my\"val
when printed
Here's how I did it for an array:
Backend
const response = await request(GRAPHQL_ENDPOINT, query)
return res.render('research/index', {
articles: JSON.stringify(response.getAllArticles) || [] // Stringify output to Frontend
})
Frontend
<script>
window.quillContent = <%- articles.replace(/=>/g, '=>') %> // I had to fix => back to fat arrow
</script>
<% const allArticles = JSON.parse(articles)
allArticles.forEach((article, i) => { %>
<div id="editor<%- i %>"></div> // Create dynamic number of divs
<% }) %>
<script>
'use strict'
hljs.configure({
languages: ['javascript']
})
window.quillContent.forEach((article, i) => {
const quill = new Quill(`#editor${i}`, { // Create dynamic number of Quill Editors
modules: {
syntax: true,
toolbar: false
},
readOnly: true,
theme: 'snow'
})
quill.setContents(JSON.parse(window.quillContent[i].content)) // Parse input from Backend
})
</script>
This code is specific to Quill when using syntax highlighting on ES6 code, but it demonstrates iterating through the array in a common manner.
The basics are the same: JSON.stringify()
Array output to Frontend, and then JSON.parse()
the Array in the Frontend when you consume it, and you may see some HTML entities get leaked in (which is feeling like an EJS templating engine issue).
@if(isset($payload))
{{--*/
$payload = json_encode($payload);
$payload = preg_replace("_\\\_", "\\\\\\", $payload);
$payload = preg_replace("/\"/", "\\\"", $payload);
/*--}}
<script>
window.__payload = JSON.parse("{!!$payload!!}");
</script>
@endif
Here's a php blade version. Payload is any object.
myObject == myObjectFrontend // true, except one is frontend and one is backend