Question: Is there a nice way to route using EJS teamplate avoiding repetition with Express server?


Is there a nice way to route using EJS teamplate avoiding repetition with Express server?

Answers 2
Added at 2017-01-04 13:01

Let's say that my app has two view: index.ejs, profile/index.ejs I want to route using express code like below.

/* GET home page. */
router.get('/', function (req, res, next) {

/* GET profile page. */
router.get('/profile', function (req, res, next) {

should both two ejs files have bootstrap link?

<link rel="stylesheet" href="">

If the answer is yes, whenever I want to render another page, should I reload style and js file from CDN?

I mean, is there a nice way to keep common contents when I change my EJS template?

nr: #1 dodano: 2017-01-04 13:01

No. You can do this easily by adding scripts and css that are used for whole application into different EJS file.

For example.

Create file called header.ejs and add in it all links and scripts.

Then in your templates just include this file, with this piece of code

   <% include header.ejs %>
   //IN HERE you can add page specific scripts or links

Hope this helps

nr: #2 dodano: 2017-01-04 18:01

There are several ways to achieve this.

1). use partials and include them in every page.

2). If you don't like including the partials in each page then you can use express-ejs-layouts or ejs-locals

For the first approach we can have a partials directory that will contain all the partials we need.

partials directory

And here are our partials

<meta charset="UTF-8">
<title>EJS Template</title>
<link ref="" rel="stylesheet">
<script src=""></script>

This scipt.js can include all the scripts that you want to include.


<script src="">      </script>

Let's say we want to include these partials in index.ejs then all we need to do is to simply use

// index.ejs
<!DOCTYPE html>
<html lang="en">
    <% include partials/head %>
  <body class="container">

      <% include partials/header %>

      <div class="jumbotron">
        <h1>This is great</h1>
        <p>Welcome to templating using EJS</p>

       <% include partials/footer %>
    <% include partials/script %>

Hope this helps !!

Source Show
◀ Wstecz