Search code examples
javascriptnode.jspug

How can I get Data int Jade


I made list page pagination. i want make some pagination number list. but i don't know how can i get data in jade.

-for(var i=0; i < #{totalCnt}; i++){
                 form(action='/topic')
                     input(type='button' name='nowPage' value=i) 
             -}

This is my Jade code #{totalCnt} is not working

app.get("/topic", function(req, res) {
  var nowPage = req.query.nowPage;
  //전체 리스트를 띄우는 기본 리스트 화면
  var sqlCnt = "select count(*) from topic";
  var sql = "SELECT id, title FROM topic ORDER BY id";
  client.query(sqlCnt, function(err, res3) {
    client.query(sql, function(err, res2) {
      if (err) {
        console.log(err);
      } else {
        if (nowPage == null || nowPage == "" || nowPage <= 1) nowPage = 1;
        var totalCnt = res3.rows;
        res.render("view", {
          topics: res2.rows,
          totalCnt: totalCnt,
          nowPage: nowPage
        });
      }
    });
  });
});

this is my javascript code to get data #{} is correct grammar?


Solution

  • You already pass the variables with the res.render function to the view file. Make Sure, that the view file is named view.pug. You passed the name of the .pug file as first parameter "view".

    In the pug specs (interpolation) you can find the following:

    If you need to include a verbatim #{, you can either escape it, or use interpolation.

    You can use the variables from the render function in your template like this:

    app.js

    app.get("/topic", function(req, res) {
        var nowPage = req.query.nowPage;
    
        client.query("select id, title from topic order by id", (err, result) => {
    
            if (!nowPage || nowPage === 1)
                nowPage = 1;
                    
            res.render("view", {
                title: 'Topics',
                topics: result.rows,
                totalCnt: result.rowCount,
                nowPage: nowPage,
                errors: err
            });
        });
    });
    

    view.pug

    h1 #{title}
    p There are !{totalCnt} topics on !{nowPage} page
    
    if topics
      ul
        for topic in topics
          li ID: #{topic.id}, Title:  #{topic.title}
    else if errors
      ul
        for error in errors
          li!= error.msg
    

    Note: I didn't escaped the count values (I used the !{} syntax) because the count values are calculated.