Skip to content

Read: 12

Dayne edited this page Dec 17, 2019 · 1 revision

EJS Partials

Partials appear to be like functions but for HTML code that you want to re-use across multiple .ejs files or "views". To call them in a view, simply use <%- include( PARTIAL_FILE ) %> as the syntax. Here some more examples:

navbar.ejs

<div class="header clearfix">
    <nav>
        <ul class="nav nav-pills pull-right">
            <li role="presentation"><a href="/">Home</a></li>
        </ul>
        <h3 class="text-muted">Node.js Blog</h3>
    </nav>
</div>

footer.ejs

<footer class="footer">
    <p>© 90210 Lawyer Stuff.</p>
</footer>

home.ejs

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Node.js Blog</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <style>
        body {
            padding-top: 20px;
            padding-bottom: 20px;
        }
        .jumbotron {
          margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <%- include('partials/navbar') %>
        <div class="jumbotron">
            <h1>All about Node</h1>
            <p class="lead">Check out our articles below!</p>
        </div>
        <div class="row">
            <div class="col-lg-12">
                <div class="list-group">
                  <!-- loop over blog posts and render them -->
                  LIST_OF_POSTS
                </div>
            </div>
        </div>
        <%- include('partials/footer') %>
    </div>
</body>
</html>

views/post.ejs:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>POST_TITLE | Node.js Blog</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <style>
        body {
            padding-top: 20px;
            padding-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <%- include('partials/navbar') %>
        <div>
            <h2>POST_TITLE</h2>
            <p>by <a href="#">POST_AUTHOR</a></p>
            <p>POST_CONTENT</p>
            <hr>
        </div>
        <%- include('partials/footer') %>
    </div>
</body>
</html>

Clone this wiki locally