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,448
  • 10
  • 11
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
  • 861
  • 1
  • 5
  • 19