user2255700
user2255700

Reputation: 113

Need help using EJS

I am exploring the use of the EJS templating system and am unsure of how to use it to get SQL data to be available to be rendered in a view.

In my app.js I have something like this:

conn.query("select name,age from people", function(err, people, moreResultSets) {
    for (var i=0;i<people.length;i++){
        console.log(people[i].NAME, "\t\t", people[i].AGE);
    }
                                       
    conn.close(function(){
	    console.log("Connection Closed");
	});
});

And I have the following code to route the proper view:

app.get('/test1', function(req, res) {
    res.render('pages/test1');
})

My confusion lies in making the people data available from the query statement to be rendered in the view. All of the examples I have seen have the variables defined locally inside the app.get code block and I am unclear how to jump from that to my situation.

Thank you for any assistance you can provide! -Andy

Upvotes: 0

Views: 49

Answers (1)

Miguel
Miguel

Reputation: 20633

Render after you have the data.

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

    conn.query("select name,age from people", function (err, people, moreResultSets) {
        res.render('pages/test1', {
            people: people
        });

        conn.close(function () {
            console.log('Connection Closed');
        });
    });

});

HTML

<% if (people) { %>
    <% for (var i = 0; i < people.length; i++) { %>
        <div><%= people[i].name %></div>
    <% } %>
<% } else { %>
   <div>No people found</div>
<% } %>

Upvotes: 1

Related Questions