Skip to content

Instantly share code, notes, and snippets.

@danschumann
Last active January 4, 2021 16:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danschumann/ae0b5bdcf2e1cd1f4b61 to your computer and use it in GitHub Desktop.
Save danschumann/ae0b5bdcf2e1cd1f4b61 to your computer and use it in GitHub Desktop.
How to pass an object from nodejs to frontend
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>
@agm1984
Copy link

agm1984 commented Sep 6, 2017

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(/=&gt;/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).

@danschumann
Copy link
Author

  @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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment