1

enter image description hereI have an HTML file named as index.html.

The file contains a JSON array data as added below.

I want to display this array using div tag, The HTML code is given below :

Code

//node js code
res.sendFile(__dirname+'/index.html',{data:JSON.stringify(data)});

//html code 
<% var d = JSON.parse(data); for (var i= 0; i < JSON.parse(data)[0].length; i++) { %>
                    <div class="col-md-12 mt-3 border-bottom p-2 chat-select ">
                        <div class="row">
                            <div class="user-chat-img">
                                <img src="img/user.jpg">
                            </div>
                            <div class="">
                                <p class="font-weight-bold"><%= d[0][i].name %></p>
                                <span>Hello I am DK Singha   </span>
                            </div>
                        </div>
                    </div>

                    <% } %>

Please suggest me how to resolve this problem.

2 Answers2

1

I found this.
res.sendfile in Node Express with passing data along

rewrite.

// NodeJS
const target = '$$$data$$$';
fs.readFile(__dirname+'/index.html', (err, html) => {
    res.send(html.replace(target, JSON.stringify(data)));
});


// HTML
<script>
var data = '$$$data$$$$';
data = JSON.parse(data)[0];
for (var i= 0; i < data.length; i++) { 
    console.log(data[i].name);
}
</script>

this is working?

seunggabi
  • 1,699
  • 12
  • 12
  • Loop is not working properly and at the place of <% var data = '$$$data$$$$'; for (var i= 0; i < JSON.parse(data)[0].length; i++) { %> and <%= d[0][i].name %> it is dislaying the same result like <% var data = '$$$data$$$$'; for (var i= 0; i < JSON.parse(data)[0].length; i++) { %> and <%= d[0][i].name %> – user3834344 Dec 26 '19 at 05:09
  • Can you suggest me How can we display data using loop? – user3834344 Dec 26 '19 at 05:11
  • I have added the picture @seunggabi – user3834344 Dec 26 '19 at 05:32
  • @user3834344 okay I understand code. You have to add script append HTML elements – seunggabi Dec 26 '19 at 05:38
  • @user3834344 https://stackoverflow.com/questions/18703780/adding-multiple-html-elements-in-a-javascript-loop – seunggabi Dec 26 '19 at 05:39
0

I suggest you to use view engine, such as twig, pug or blade. If you are working with Express, it's super easy to setup and use. You would be able to pass your data to your view in your Express router like this:

app.get('/', function (req, res) {
    res.render('index', { title: 'Hey', message: 'Hello there!'});
});

And then use your JSON variables in your view, you can see the twig documentation here: Twig Doc

For example here, it would be {{ title }} or {{ message }} to use those variables. You can implement for loop, conditions and more using view engines.

Lucas Gras
  • 961
  • 1
  • 7
  • 22