Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
express
node.js
ejs
communitycreator

Create an Express server with the EJS templating engine

Nasreen

In today’s simple application, we will learn how to create a simple server with the Express Node.js application framework. In this app, we will also learn how to use the EJS templating engine to serve HTML and style your apps with plain JavaScript.

There are a variety of JavaScript templating engines available on the web; however, EJS stands out because of its simpler syntax and easy understandability.

Detailed documentation about EJS can be found here.

Implementation

To begin our app, we create an empty main.js file and install the required dependencies. First, we need to create the package.json file with the following command.

npm init -y

Next, install express and ejs into your app.

npm install express ejs

Now, we will write the express boiler plate code in our main.js file in order to create our server.

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

The code above will make the server run at port:3000 and send a ‘Hello World’ message on the home route, which is denoted by /.

In this manner, we can create as many routes as we want for our application. In this demo application, we will only create a home route and an about route in the following manner:

const express = require("express");
const app = express();
const path = require("path");

app.use(express.urlencoded({ extended: false }));

app.get("/", (req, res) => {
res.send("Welcome to the Home page")
});

app.get("/about", () => {
res.send("Welcome to the About Us page")
})

app.listen(3000, (req, res) => {
  console.log("server is running");
});

Now, we can move on to create a pets object in the home route. We want to render it on the home page of our app, but we don’t just want to show a JavaScript object on the home page. Instead, we want a beautiful application to be displayed.

To achieve this, we will create a “views” folder in our project directory. We then create a home.ejs file where we can write the desired HTML for our pets object from the main.js file, to be displayed on the home page of our app.

First, I will update the home route on the main.js file to render the pets object.

app.get("/", (req, res) => {
  res.render("home", {
    pets: [
      {
        name: "Meowsalot",
        description:
        "From the tiny Rusty-spotted cat of Sri Lanka to the massive Siberian tiger of the Russian Far East, there are 40 species of wild cats in the world, and each of them is as beautiful as it is unique.Most of us know lions, tigers, jaguars and leopards, but what are all the other types of wild cats out there? If you consider yourself a cat person or simply curious about these charismatic animals, read on to meet the family. They are the most loved and cute species found on the land.",
        species: "cat",
        image: "https://540934-1733880-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2020/05/Eurasian-lynx-AdobeStock_246336076-1024x683.jpg"
      },
      { name: "Barksalot", 
      description: "Dogs are the most variable mammal on earth with around 450 globally recognized dog breeds.[10] In the Victorian era, directed human selection developed the modern dog breeds, which resulted in a vast range of phenotypes. Most breeds were derived from small numbers of founders within the last 200 years, and since then dogs have undergone rapid phenotypic change and were formed into today's modern breeds due to artificial selection imposed by humans.",
      species: "dog" ,
    image: "https://upload.wikimedia.org/wikipedia/commons/e/e0/Dog_niemiecki_%C5%BC%C3%B3%C5%82ty_LM980.jpg"},
    ],
  });
});

Next, I will set our app to use the EJS view engine.

app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));

Here, I will also create a public folder in the root of our app, and create a style.css file there to include the necessary styling for our app. Also, don’t forget to set the app to use the assets from the public folder, as follows:

app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));

Now, let’s move to the home.ejs file, where we will call our pets object and render it in the form of a mix of HTML and JavaScript.

<body>
<nav>
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/about">About Us</a></li>
    </ul>
</nav>

    <h1>Welcome to the Home Page</h1>
<div class="container">
  
        <% pets.forEach(pet => { %>
            <li>
                <h2><%= pet.name %> </h2>
                <p>(<%= pet.species %>)</p>
            <img src= "<%= pet.image %>"/>
            <p class="text"><%=pet.description %></p>
            </li>
                <% }) %>
    
   
</div>
   
</body>

Remember, to use EJS, you have to use the <% symbol and also end it by %>. In the middle, you can use plain old HTML. In all those instances where you make use of any variable or evaluate something, you will also include an = sign like this: <%=.

I have linked both the home.ejs and about.ejs to our style.css file present in the public folder to do the necessary styling required for our application. You can find all the styles here.

Below is the finished look of the application.

Alt Text

You can navigate to the Home page and About Us page from the navbar present at the top.

The complete code of the application can be found here.

RELATED TAGS

javascript
express
node.js
ejs
communitycreator
RELATED COURSES

View all Courses

Keep Exploring