Dynamic Content

node.js

Hyerang Raina Kim
2 min readAug 23, 2020

Sharing Data Across Requests & Users

If we create product array in admin.js and put data in it,

const products = []...router.post('/add-product', (req,res,next) => {
products.push({title: req.body.title})
res.redirect('/');
});

we can export the data to share its data in other files.

exports.products = products;

Then, in shop.js, import the data from admin.js like below,

const adminData = require('./admin');

and access it with the syntax below.

console.log(adminData.products);

Templating Engines

>>> npm install --save ejs pug express-handlebars
  • app.set: set the global configuration value
app.set('view engine', 'pug');
app.set('views','views'

Then we add the shop.pug file under the views folder, and we’ll use

res.render('shop');

syntax in shop.js so that express.js will look for pug file under views file and render it as a normal html file.

Outputting Dynamic Data

First, we store the input data in the constant variable named products. Then, we pass the

shop.js

router.get('/', (req,res,next) => {
const products = adminData.products;
res.render('shop', {prods: products, docTitle: 'Shop'});
});

shop.pug

main
if prods.length > 0
.grid
each product in prods
article.card.product-item
header.card__header
h1.product__title #{product.title}
div.card__image
img(src="<img_url>", alt="A Book")
div.card__content
h2.product__price $19.99
p.product__description A very interesting book about so many even more interesting things!
.card__actions
button.btn Add to Cart

By using each … in … syntax, it works as a for loop.

Adding a Layout

Most pages have similar layouts so copying and pasting over and over again whenever creating a new file is cumbersome.

  • Create a sub folder name layouts under views.
  • Create a new file name main-layout.pug

main-layout.pug

<!DOCTYPE html>
html(lang="en")
head
meta(charset="UTF-8")
meta(name="viewport", content="width=device-width, initial-scale=1.0")
meta(http-equiv="X-UA-Compatible", content="ie=edge")
title Document
link(rel="stylesheet", href="/css/main.css")
block styles
body
header.main-header
nav.main-header__nav
ul.main-header__item-list
li.main-header__item
a(href="/") Shop
li.main-header__item
a(href="/admin/add-product") Add Product
block content

Block holds the dynamic content.

404.pug

extends layouts/main-layout.pugblock content
h1 Page Not Found!

We’re now passing a new key path

admin.js

res.render('add-product', {pageTitle: 'Add Product', path: '/admin/add-product'});

so that we can clarify which tab is active.

In main-layout.pug,

a(href="/admin/add-product", class=(path === '/admin/add-product' ? 'active' : '')) Add Product

conditionally add the active class.

--

--