Andrea Fresa
Andrea Fresa

Reputation: 341

Render HTML Page with Json data


I have this issue:
I have a get request that I serve using router.get (Express). In this function I use to take datas from my sql db. Now i have this data in JSON format.
I want to pass the json datas to handlebars and to send the response to the client with the datas rendered inside the html only (Render is completely made on server side).
Maybe I' m getting a little bit confusing:
Is there a solution for what I want to do?


Express:

//CHAT
router.get('/chatlist', ensureAuthenticated, (req,res)=>{
    let mittente = req.user.id;
    findUsersChat(mittente)
    .then(Chats=>{
        getChatData(Chats,mittente).then(ChatList=>{
            console.log("Lista2: " +ChatList);
            var obj=JSON.parse(ChatList);
            res.render('chatlist') ;
        })
        .catch(err=>console.log(err))

    });

})


Handlebars

<section id="gigs" class="container">
    <h1>Chats Available</h1>

        {{#each obj}}
        <h1>{{Nome}}</h1>
        <div class="form-group">
          <form method="POST" action="/users/chat">  
            <p>Utente numero : {{@index}}</p>
            <label for="name" value={{Nome}}>{{Nome}}</label>

          </form>

        </div>
        {{/each}}
  </section>

Upvotes: 0

Views: 1415

Answers (1)

Mihai
Mihai

Reputation: 10717

It looks like you are not passing the array (ChatList) to your view. You can do that by changing your code to this:

...
        getChatData(Chats,mittente).then(ChatList=>{
            console.log("Lista2: " +ChatList);
            res.render('chatlist', {objects: ChatList}) ;
        })
...

By doing this an array "objects" will be available in your view and you can iterator over it.

Your page now should become:

<section id="gigs" class="container">
    <h1>Chats Available</h1>

        {{#each objects}}
        <h1>{{./Nome}}</h1>
        <div class="form-group">
          <form method="POST" action="/users/chat">  
            <p>Utente numero : {{@index}}</p>
            <label for="name" value={{./Nome}}>{{./Nome}}</label>

          </form>

        </div>
        {{/each}}
  </section>

Upvotes: 1

Related Questions