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

Question

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

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

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) {
    res.render('index');
});

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

should both two ejs files have bootstrap link?

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

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?

Answers to

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

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

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

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

//partials/head.ejs
<meta charset="UTF-8">
<title>EJS Template</title>
<link ref="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

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

//partials/script.js   

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">      </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">
  <head>
    <% include partials/head %>
  </head>
  <body class="container">

    <header>
      <% include partials/header %>
    </header>

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

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

Hope this helps !!

Source Show
◀ Wstecz