1

I'm new to Node.js/Express.js and I've been reading a lot, but I confess that perhaps I'm still to stick into the PHP paradigm. I'm thinking to shift my site's server from PHP to Express.js, but there are certain issues that I still cannot figure out.

For example in PHP, if I wanted to dynamically build an enormous HTML table from an Object or Array I would simply do something like:

<table>
  <?php foreach ($my_array as $key => $value) { 
    echo "<tr><td>".$key."</td><td>".$value."</td></tr>";
  }?>
</table>

How would I do that in Express.js with or without Jade?

5
  • 1
    You have multiple options from handlebarsjs.com reactjs.org vuejs.org and many more Commented Dec 19, 2017 at 19:16
  • @asosnovsky Could you kindly be more descriptive? Commented Dec 19, 2017 at 19:23
  • 1
    Express on its own does not have a way to do it, you need to either integrate a template processing framework like handlebarsjs.com or shift how you think of the application be adding a client-side view-layer like reactjs.org or vuejs.org. I think you go for handlebars, as it would be closer to how you use to work in php (with slight different syntax) Commented Dec 19, 2017 at 19:26
  • @asosnovsky Could you kindly provide here an example with handlebarsjs and I'd set your answer as the solution? Thank you in advance Commented Dec 19, 2017 at 20:48
  • someone made a downvote. Reasons should be provided according to guidelines Commented Dec 20, 2017 at 0:05

1 Answer 1

4

Sure you can do the same thing with express:

app.get('/', (req, res) => {

  let obj = { 1: 'one', 2: 'two', 3: 'three' }

  let result = '<table>';
  for (let el in obj) {
    result += "<tr><td>" + el + "</td><td>" + obj[el] + "</td></tr>";
  }
  result += '</table>';

  res.send(result);

})

But it's a good idea to decouple data from view with the use of a template engine like jade:

index.pug:

table
  each value, key in data
    tr
      td #{key}
      td #{value}

server.js:

app.get('/', (req, res) => {
  let obj = { 1: 'one', 2: 'two', 3: 'three' }
  res.render('index', { data: obj })
})
Sign up to request clarification or add additional context in comments.

3 Comments

Very interesting indeed. Thus in jade the expression each value, key in data fills HTML to the browser according to the data object which you sent in server.js
What I mean is that I thought it was impossible to make a 'static' view model be filled immensely with data from an object. Thus it's very similar when jQuery fills 'static' html. Thanks :)
Sure, and you can use any template engine that suits you, like handlebars as suggested by asosnovsky in his comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.