Guide to effectively utilizing partials in express using ejs

I am developing a web application where the layout remains consistent, except for one specific <div>. Currently, I am using routes to handle links, but it feels inefficient to reload the entire layout.ejs file when only the <div> needs to be updated.

What changes should I make in my layout.ejs file? Here is the current content:

<!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 have been considering utilizing AJAX for this purpose, but I have also heard about the benefits of using partial views. Setting this up seems daunting, especially with the possibility of incorporating WebSockets instead of AJAX. Can anyone provide guidance on how to proceed with this setup?

I apologize if this question seems rudimentary. I am struggling with understanding the documentation on this topic.

Thank you!

Answer №1

After some troubleshooting, I've come up with the solution.

To load a partial in the view using EJS, you can call `partial(filename)`. For example, if we have three files in the `views/` directory: 1. layout.ejs 2. index.ejs 3. header.ejs and the content of index.ejs is : then, start the server, browse it, and you will see `header.ejs` loaded into `index.ejs`.

UPDATE: In Express version >=3.0, there is no longer the partial() function. Instead, you can use <% include xxx.file %>, or utilize another module called "express-partials". You can find this module on Github for further information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`Node.JS app having issue displaying AngularJS code on Localhost`

I have successfully created a Node.JS application, where I implemented my own HTTP server within the main JS file. The HTML and CSS render correctly on localhost, and even JQuery works when imported via CDN. However, I am facing an issue with displaying ba ...

Managing MongoDB connections efficiently in a Node.js environment

I am currently working on a website using the node-mongodb-native driver with mongodb. My query is regarding how to establish a single mongodb connection and then utilize it in the "users" collection in user.js and the "posts" collection in comment.js Th ...

When running npm install, the dist folder is not automatically generated

I found a helpful tutorial at this link for creating a Grafana plugin. However, when I tried copying the code from this link to my test server (without the dist/ folder) and ran npm install, it did not generate a new dist/ folder but created a node_module ...

"Encountering issues with npm failing to install node_modules

When attempting to install Angular using npm, I noticed that it is not creating a node_modules directory. This issue occured while following the steps shown in the screenshot below: MacBook-Pro-di-Sandro:~ sandropalmieri$ cd Documents/mycode/ MacBook-Pr ...

The function soap.createClientAsync is not defined and is throwing a TypeError

Encountering an issue with the soap npm module while developing an application in Meteor. Here is the code snippet causing the error: soap.createClientAsync(url).then((client) => { return client.someMethod(soapArgs, function(err, result) { ...

The passport.authenticate function will not run on a specific route

My express project utilizes the Passport-jwt Strategy for authentication. You can find my passport-jwt config in the /config/passport.js directory. var JwtStrategy = require('passport-jwt') .Strategy, ExtractJwt = require('passport-jwt&a ...

Steps to Embed an Image File in a MERN Stack Application

I'm attempting to load an image from a file inline because I need to pass data (the image name), but nothing seems to be working. It doesn't work whether the image is inside the src folder or outside in the public folder. Here's what I trie ...

What causes the MySQL pool to become undefined when accessed in a member function after being assigned to a member variable?

I am currently working on setting up a connection pool for queries in my project. I have created a simple class where the connection pool is assigned to a member variable. The issue I am facing is that even though the member variable is correctly set in th ...

Encountering an issue when trying to execute the npm start command in the Windows 10 command prompt

Need assistance with a React error. I encounter this screen when attempting to run the command npm start after creating a new React project. ...

The process of passing a variable between two routes in an Express application

Is there a method to pass variables between two routes in expressJS without setting it as a global variable? For example, if we have the following routes: exports.routeOne = (req,res) => { var myVariable='this is the variable to be shared'; ...

Encountering difficulties installing socket.io using npm on Centos 6.4

Currently in the process of setting up socket.io via npm on a fresh Centos 6.4 (running on a virtual machine). (using root access temporarily for testing purposes) [root@localhost lib]# npm cache clean [root@localhost lib]# npm install socket.io npm http ...

Looking for clarification on Jade syntax

Currently, I am exploring Huge's latest Styleguide templates and delving into Jade syntax. However, despite my efforts, I haven't been able to locate any documentation on how the image paths were created by the author. The specific syntax used is ...

"An error message stating 'Express: The body is not defined when

I'm encountering an issue while trying to extract data from a post request using express. Despite creating the request in Postman, the req.body appears empty (console.log displays 'req {}'). I have attempted various solutions and consulted s ...

The Next.js API call for /api/contact was successful, but no response was sent back, potentially causing delays in processing other requests

Encountering the issue of API resolved without sending a response for /api/contact, this may result in stalled request on a specific API route within Next.js. Despite successfully sending emails using sendgrid, I am unable to receive a response to handle e ...

Utilizing Express.js and AJAX to transfer JSON data from the server to the client

Having trouble sending JSON from Express.js back to the client, and I can't seem to figure out what's going wrong. routes/editor.js exports.save = function(req, res){ fs.readFile(__dirname + "/../public/index.html", function (err, data) { ...

What steps should I take to create code that can generate a JWT token for user authentication and authorization?

I'm struggling to get this working. I have a dilemma with two files: permissionCtrl.js and tokenCtrl.js. My tech stack includes nJWT, Node.js/Express.js, Sequelize & Postgres. The permission file contains a function called hasPermission that is linke ...

What is the best way to establish a connection between two services in a Docker-compose setup so that they are able to communicate with each

I'm new to Docker and facing challenges in connecting two separate services using docker-compose. I need to be able to write to a database and read from it. Additionally, each container should be able to ping the other one. When I run docker exec -ti ...

Is the express-session expiration object not the appropriate data type?

Occasionally, my nodejs program — which is built with the express v4.12.2 and express-session v1.13.0 packages — encounters a TypeError exception leading to a crash: /app/node_modules/express-session/node_modules/cookie/index.js:136 if (opt.expires) ...

The login request through Express and Passport does not complete or finalize

I have implemented authentication in my express app using passport, passport-local and passport-jwt. The login code below generates a token which is then sent back via the response object. However, when attempting to login using Postman, the request never ...

Can you explain the distinction between cookies' maxAge and expiration date?

In my NodeJS Express app, I am utilizing cookies for certain features and need to set the cookie duration to one month. To achieve this, I have configured the cookie's maxAge property as days*hoursPerDay*minutesPerHour*secondsPerMinute*1000, which tr ...