DEV Community

Ahmet Meliksah Akdeniz
Ahmet Meliksah Akdeniz

Posted on

Blog Project Part 2: Template Engine

Create Public Folder, Put Your Static Files in It

Starting files for Blog project: https://drive.google.com/file/d/1yWS-hrxi7MwsyU2YxpcCpfXd6ilws1Xw/view

  • This is a homework project from Patika.dev and they provide starting files for this project.

Image description

Once that's done, save public folder on the app app.use(express.static("public"))

EJS Module

EJS stands for Embedded JavaScript templates. It will make our code more functional because we won't be repetitive anymore.
Download ejs type npm i ejs and hit enter on terminal. Then, add const ejs = require("ejs") on app.js file to import ejs.
Also, add this on your code app.set("view engine", "ejs").

So far your code should look like this:

const express = require("express"); // imported express
const ejs = require("ejs");
const app = express(); // assigned express func to app constant

// ENGINE SET
app.set("view engine", "ejs"); // set engine as ejs that looks at view folder
app.use(express.static("public")); // look at public folder for static parts of the webapp
Enter fullscreen mode Exit fullscreen mode

Now, let's get the routes. Since I talked about them in one of my previous blogs, I won't bother to get it into detail here.

// ROUTES
app.get("/", (req, res) => {
  res.render("index");
});

app.get("/about", (req, res) => {
  res.render("about");
});

app.get("/add_post", (req, res) => {
  res.render("add_post");
});
Enter fullscreen mode Exit fullscreen mode

Precisely, the code above: When root URL entered, render me the index file. When /about URL entered, render me the about file, and when /add_post URL entered render me the add_post file. res.render() method renders files.
I added those files in my views folder, you can see it here:

Image description

Partials

I made a partials file where I store repeated codes, such as header, footer and navigation. They are in .ejs format and not HTML.

Call an .ejs file in your code: <%- include("partials/_header.ejs") -%>. Put *___ in the beginnings of your ejs file, it's a convention.
To observe the full code please check out my Github profile

That's it for now. Take care and keep coding!

Top comments (0)