node.js EJS templating with js fetch and rendering a data driven partial

67 views Asked by At

I am not super familiar with partials so this may not even be the right way to go... Here is what I am looking to do.

Have a basic index page that loads a list of, let's call them configs. These configs are pulled form a data base and rendered on the index view using basic ejs syntax.

<ul>
    <% configs.forEach(function(obj) { %>
        <li onclick="configClickHandler('<%= obj.id %>')" class="configLink">
           Name: <%= obj.title %>
        </li>
    <% }); %>
</ul>

When I click on the

  • I make a fetch call to the backed which returns a single JSON object

    I would like to use that object to update the UI and display the details of the object.

    I know I can do this with javascript, build out the HTML in a function and then place it on the page but I was wondering if I could leverage an EJS partial to do this?

    Something like

    <%- include('partials/config, {data: DATAFROMAPI}) %>

    Kind of react like where the partial is like a component...

    Again, I may be all wrong here, are partials designed to be used like this? Is there a better approach to creating reusable data bindable components ( and not using react )?

  • 1

    There are 1 answers

    0
    Eyas Valdez On

    I don't think you'll find a native ejs solution for this. ejs doesn't ship any of its embedded syntax to the client, so unlike an SPA like React it won't trigger a re-render the DOM on state change under the hood.

    Also basic html doesn't store state between renders unless you're utilizing window.localStorage, so assuming you aren't using window.localStorage then you'll want to avoid triggering a re-render or else the JSON you pulled from your database will be lost on each click and the page will won't render anything.

    I'd recommend appending child element nodes to the parent node after your configClickHandler function pulls your JSON data.

    Without knowing your full implementation, it would look something like:

    <script>
     const configClickHandler = (id) => {
        const some_json_data = someOperation();
        const li_node = document.createElement("li");
        const text = document.createTextNode(JSON.stringify(some_json_data));  
        li_node.appendChild(text);  
        document.getElementById(id).appendChild(li_node);
     }
    </script>
    
    <ul>
        <% configs.forEach(function(obj) { %>
            <li id=<%= obj.id %> onclick="configClickHandler('<%= obj.id %>')" class="configLink">
               Name: <%= obj.title %>
            </li>
            
        <% }); %>
    </ul>
    

    I added an id attribute, but you can use a whole bunch of ways to query DOM nodes.