trolkura trolkura - 2 months ago 12
Jade Question

Dynamicly creating elements inside pug(jade)

I am trying to dynamicly create elements inside pug template.

I retrieve an informations from database using basic command

db.component.findAll().then(function(component){
res.render('stock' ,{ table:component})
})


the template that the content is supposed to be created is

.tbl-content
table(cellpadding='0', cellspacing='0', border='0')
tbody
- row in table
tr
td= "#{row.name}"
td= "#{row.storage}"


I have checked the syntax and it should be correct , but the result is complete wrong. It takes
row in table
as string e.g content and show it on page , same with
"#{row.name}"
and
"#{row.storage}"


Am i using some outdated syntax or is my approach completely wrong?

Thanks!

Answer

Your used syntax seems to be wrong if you're using the default pug template engine for Node.js

You can make it work by:

.tbl-content
    table(cellpadding='0', cellspacing='0', border='0')
      tbody
       each row in table
            tr
                td= row.name
                td= row.storage

Explaned in more detail in the documentation: https://pugjs.org/language/iteration.html

My complete simple Node.js test file with which I did the successfull testing was:

var express = require('express');
var app = express();
app.set('view engine', 'pug');

var component = [
    {name:'myName', storage:'myStorage'},
    {name:'myName2', storage:'myStorage2'}
];
app.get('/table', function (req, res) {
    res.render('stock' ,{ table:component});
});

app.listen(3000);

It results in the response:

<div class="tbl-content">
 <table cellpadding="0" cellspacing="0" border="0">
  <tbody>
   <tr><td>myName</td><td>myStorage</td></tr>
   <tr><td>myName2</td><td>myStorage2</td></tr>
  </tbody>
 </table>
</div>