Question: Using an ejs partial template breaks JSON.stringify

Question

Using an ejs partial template breaks JSON.stringify

Answers 0
Added at 2017-11-08 15:11
Tags
Question

I'm using an ejs template to do server-side rendering within a sails app. In the template, I'm sending along a var inside a script tag to use on the client side, like this:

<script>
    var galleryObj = <%- JSON.stringify(gallery) %>;
</script>

This works fine.

However, when I add a partial higher up in the template, JSON.stringify throws a "circular object" error. So, the following Throws the error in the template file:

<div id="components">
    <% for (var idx = 0; idx < gallery.components.length; idx++) { %>
        <%- partial('partials/component', gallery.components[idx]) %>
    <% } %>
</div>

<script>
    var galleryObj = <%- JSON.stringify(gallery) %>;
</script>

However, it works with this modification:

<div id="components">
    <% var galleryJSON = JSON.stringify(gallery); %>
    <% for (var idx = 0; idx < gallery.components.length; idx++) { %>
        <%- partial('partials/component', gallery.components[idx]) %>
    <% } %>
</div>

<script>
    var galleryObj = <%- galleryJSON %>;
</script>

Clearly, using the partial is modifying the gallery object as used by the template, but I'm not sure how.

Some notes to help debug:

  • the partial command within the template may be specific to using ejs from a sails app. I think "plain" ejs uses include to similar effect.
  • each gallery.components[idx] have some property keys that match property keys for the whole gallery object, for example createdAt, etc.

Can anyone tell me what's going on?

Answers to

Using an ejs partial template breaks JSON.stringify

Source Show
◀ Wstecz