In the post ExpressJS: Pug Template Engine Integration With Examples we have seen how you can use Pug template with Express.js app. In this post we'll see how to iterate over an array or object in Pug template.
Iteration in Pug
In Pug you can iterate over values using one of the following-
- each
- while
For example, using each with an array of values.
ul each val in [1, 2, 3, 4, 5] li= val
This transforms to an HTML
<ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul>
Using each to iterate over an object and accessing both key and value.
ul each val, key in {name:'Badal', age: 34, gender:'M'} li= key + ': ' + val
This transforms to an HTML
<ul> <li>name: Badal</li> <li>age: 34</li> <li>gender: M</li> </ul>
Using while to create a loop
- var n = 0; ul while n < 5 li= n++
This transforms to an HTML
<ul> <li>0</li> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul>
Express.js - Pug iteration example
Let's assume we have an array of User objects which we want to iterate and display in our view named 'test' which is created as a Pug template.
app.js
const express = require('express'); const app = express(); const port = 3000; const path = require('path'); app.use(express.static(path.join(__dirname, 'public'))); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); const users = [{name:'Reene', age: 28, gender:'F'}, {name:'Badal', age: 34, gender:'M'}, {name:'Vidyut', age: 25, gender:'M'}, {name:'Dhriti', age: 29, gender:'F'} ] app.get('/', (req, res) => { res.render('test', {users: users, pageTitle: 'User Page'}); }) app.listen(port, () => { console.log(`Example app listening on port ${port}`) })
public\css\main.css
CSS used for styling.
.main{ padding: 0; margin: 0; font-family: sans-serif; } .header{ width: 100%; height: 3rem; text-align: center; background-color: #6d70a8; padding: 1 2rem; color: antiquewhite; }
views\test.pug
doctype html html(lang="en") head meta(charset="UTF-8") meta(name="viewport", content="width=device-width, initial-scale=1.0") title #{pageTitle} link(rel="stylesheet", href="/css/main.css") body h2.header A pug template table each user in users tr td= user.name td= user.age td #{user.gender}
As you can see iteration is done using each, in each iteration one user object is taken from the users array and the properties are displayed. A table is created where each row represents one user record.
This is the generated HTML that you can view by going to page source.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Page</title> <link rel="stylesheet" href="/css/main.css"> </head> <body> <h2 class="header">A pug template</h2> <table> <tr> <td>Reene</td> <td>28</td> <td>F</td> </tr> <tr> <td>Badal</td> <td>34</td> <td>M</td> </tr> <tr> <td>Vidyut</td> <td>25</td> <td>M</td> </tr> <tr> <td>Dhriti</td> <td>29</td> <td>F</td> </tr> </table> </body> </html>
Getting the index
You can also get the index as you iterate. Here is the same Pug template as used above with the inclusion of index to get serial number.
doctype html html(lang="en") head meta(charset="UTF-8") meta(name="viewport", content="width=device-width, initial-scale=1.0") title #{pageTitle} link(rel="stylesheet", href="/css/main.css") body h2.header A pug template table each user, index in users tr td= index+1+'.' td= user.name td= user.age td #{user.gender}
If you run app.js and then access http://localhost:3000/
Pug object iteration ExpreeeJS example
If you want to iterate an object and extract the (key, value) pairs.
app.js
const express = require('express'); const app = express(); const port = 3000; const path = require('path'); app.use(express.static(path.join(__dirname, 'public'))); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); //Object to be iterated const user = {name:'Reene', age: 28, gender:'F'}; app.get('/', (req, res) => { res.render('test', {user: user, pageTitle: 'User Page'}); }) app.listen(port, () => { console.log(`Example app listening on port ${port}`) })
views\test.pug
doctype html html(lang="en") head meta(charset="UTF-8") meta(name="viewport", content="width=device-width, initial-scale=1.0") title #{pageTitle} link(rel="stylesheet", href="/css/main.css") body h2.header A pug template ul each val, key in user li= key.charAt(0).toUpperCase() + key.substr(1).toLowerCase() + ': ' + val
CSS remains the same as used in the above example.
With that you'll get the result as-
Name: Reene Age: 28 Gender: F
That's all for the topic ExpressJS: Pug Template Iteration Examples. If something is missing or you have something to share about the topic please write a comment.
You may also like
- ExpressJS: Pug Conditionals
- ExpressJS: Pug Template Inheritance
- ExpressJS Query Parameters
- Using express-generator to Create ExpressJS App Structure
- Express res.sendFile() Method With Examples
- Java Callable And Future With Examples
- this in Java With Examples
- Write a File Asynchronously in Java
- HTTP PUT Method in React - fetch, Axios
- Spring Bean Scopes
No comments:
Post a Comment