Search code examples
javascriptnode.jshandlebars.jstemplatingexpress-handlebars

Partials not being rendered on dynamic webpage


I created a handlebar for my index.html file so when user visits http://localhost:3000/ [the root] it displays a dynamic version of my index.html. However, when the page loads, everything loads except for the partials I have included?

Here is the part of my page handlebar where I put the partials (newView.handlebar):

.
.
<main class="twit-container">

    {{#each twitData}}    //will iterate/insert data for the amount of objects in the array being passed in server.js
        {{> newTwit}}  //the name of my partial template
    {{/each}}

</main>
.
.etc...

and below is my server.js code (where i think the issue might be):

var path = require('path');
var express = require('express');
var exphbs = require('express-handlebars');
var fs = require('fs');
var app = express();

app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

var port = process.env.PORT || 3000;

var rawData = fs.readFileSync('./twitData.json');
var twitData = JSON.parse(rawData); //get the tweet data (text/authors)


app.get('/', function (req, res) {

  res.status(200).render('newView', {data: twitData});

});

app.use(express.static('public'));

app.get('*', function (req, res) {
  res.status(404).sendFile(path.join(__dirname, 'public', '404.html'));
});

app.listen(port, function () {
  console.log("== Server is listening on port", port);
});

Solution

  • You're iterating over twitData but you're never sending it to the view.

    <main class="twit-container">
    
        {{#each twitData}}    //will iterate/insert data for the amount of objects in the array being passed in server.js
            {{> newTwit}}  //the name of my partial template
        {{/each}}
    
    </main>
    

    You need to send it like this:

    res.status(200).render('newView', { twitData });
    

    Otherwise you will need to use: {{#each data}}.