Qcom
Qcom

Reputation: 19213

How to properly use partial views in express with ejs?

I have a web app were the entire layout remains constant except for one <div>. Currently, I'm just using routes to handle links and it seems like quite a waste to reload the rest of the layout.ejs file where the only thing I wish to change is my <div>.

What would I have to change in my layout.ejs file? Here is my current file:

<!DOCTYPE html>
<html lan="en">
  <head>
    <title><%= title %></title>
    <link rel="stylesheet" href="/stylesheets/reset.css">
    <link rel='stylesheet' href='/stylesheets/style.css' />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script src="/nowjs/now.js"></script>
    <script src="/javascripts/chat.js"></script>
  </head>
  <body>
    <div id="wrapper">
        <div id="header">
        </div>
        <div id="chat">
            <input type="text" id="text-input">
            <input type="button" value="Send" id="send-button">
        </div>
        <div id="content">
            <%- body %>
        </div>
        <div id="rooms">
        </div>
        <div id="footer">
            <div id="footer_links">
                <a href="/">Home</a> | <a href="/about">About</a> | <a href="/contact">Contact</a>
            </div>
        </div>
    </div>
  </body>
</html>

I was thinking about using AJAX to use this, but I've heard some good things about using partial views. I'm just not sure at all about how to set this up. Also, I've heard that it's possible to use WebSockets with partial views instead of AJAX. Is this a good idea, or even possible?

Sorry this may be straightforward. I'm having a difficult time with the documentation.

Thanks!

Upvotes: 4

Views: 6327

Answers (1)

ijse
ijse

Reputation: 3035

I just worked it out.

You can call `partial(filename)` in the view to load the partial. say we use EJS, and there is three files in `views/`: 1. layout.ejs 2. index.ejs 3. header.ejs and the content of index.ejs is : then, start the server, browser it, you will see `header.ejs` is loaded to `index.ejs`.

!!! UPDATE

In the express version >=3.0, there is no partial() any more. But we can use <% include xxx.file %>, or just use another module: "express-partials". Please search it on Github.

Upvotes: 7

Related Questions