Tips for choosing specific CSS in a Pug file using the 'include' feature based on the route

I am looking to create a dynamic page that can choose the appropriate CSS based on a routes.js file. My development is in node.js and pug, and I have explored different methods attempting to implement this functionality.

routes.js file

router.get("/", (req,res) => {
const indexCss = "rel='stylesheet' href='index.css' "
res.render("index"), {css:indexCss};
});

index.pug file

head
    link(#{css})
    title Index Page

Regrettably, my initial approach did not yield the desired results. I considered using link with req and body-parser but found it to be ineffective.

I believe implementing this feature would greatly benefit the organization and brevity of the code by allowing for a partial head inclusion with specified CSS from the routes.js file.

Despite my efforts, I find myself at an impasse. Does anyone have suggestions or ideas on how to achieve this?

Answer №1

When using Pug, attribute interpolation is not handled in the same way. To pass a variable containing a stylesheet path from the router to Pug, follow this method:

routes.js

router.get('/', (req,res) => {
  const cssPath = 'index.css'
  res.render('index', { cssPath })
})

index.pug

head
  link(rel='stylesheet', href= cssPath)
  title Index Page

For more information on Pug attribute interpolation, check out the Pug documentation.

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

The input[type="submit"][disabled] is malfunctioning on IE8

My input submit button has 3 different states: Active : Orange button Mouse down : Dark gray button Disabled : Light gray button <input type="submit" id="savebtn" class="save_button"/> CSS: .save_button { background: url('/Images/save_but ...

A guide on activating the Bootstrap v5 Offcanvas with toggle buttons

How can I trigger the Bootstrap V5 Offcanvas using Bootstrap switches? I want the Offcanvas to open when the switch is checked and close when the Offcanvas is closed. Sample Code : <!-- Using checkbox switches to open the offcanvas --> <div class ...

What is the method to successfully validate a unique key with Mongoose only if the other key is distinct?

Imagine a scenario where we define this model : const userSchema = new mongoose.Schema({ username: { type: String, unique: true, uniqueCaseInsensitive: true, required: true, }, organisation: { type: Schema.Types.ObjectId, ref: ...

Encountering a problem creating a hover overlay effect on a transparent PNG image within a parent div that has a background color

I'm struggling with creating an overlay hover effect on an image that has transparency. The issue I'm facing is that the black background of the parent div element is filling in the transparent parts of the PNG image, making it look like those ar ...

The button is not properly connected to the input

My dilemma involves attaching the clear button to the search input field, resulting in an unexpected outcome: https://i.sstatic.net/igkpx.jpg The issue seems to be linked to the "Black Dashboard PRO" theme that I am currently using. <form> < ...

Issue with triggering HTTP request from Angular 2 to Node server

My Http call to the node server is not being triggered. The call starts from the component below: @Component({ selector: 'app-special-value', templateUrl: './special-value.component.html', styleUrls: ['./special-value.compo ...

Tips for querying orchestrate.io

Recently, I found myself in need of a user-friendly database for a small highscore system in my game development projects using JavaScript. Through the Github student developer pack, I came across Orchestrate.io. After discovering a suitable driver module ...

You have encountered an error: [ERR_HTTP_HEADERS_SENT]. This means that you cannot set headers after they have already been sent to the client, even if a return

I've encountered a 'Cannot set headers after they are sent to the client' error with the /api/users/profile route and have been attempting to resolve it. I stumbled upon some solutions on stackoverflow suggesting to add a return statement - ...

Creating a MongoDB schema for organizing users, roles, and their associated permissions

Hey there! I'm currently working on developing a MERN application that will involve different types of users such as managers, associates, and super admins. Each user will have their own unique user ID, role, and set of permissions which will determin ...

Ways to upgrade the version in package.json

I am looking to enhance the version by extracting it from the package JSON file, which is currently 1.1.1. Once extracted, I plan to add the build number to create a new version format of 1.1.1-1, and then proceed to update the version field within the pac ...

Disabling hover effects for mobile devices

I've been searching for a solution to this problem, but nothing seems to work for me. In mobile viewports, I have a dropdown menu with styles applied on :hover, which shouldn't be active due to usability reasons. The structure of the dropdown i ...

Apply the active class to a section in the menu

I am exploring how to dynamically add the "active" class to a specific section of my menu based on which link within that section has been clicked. After successfully implementing the active class functionality for individual links using jQuery, I am confi ...

Guide on using native Ajax in NodeJS to post an object via a request

I am attempting to send the value of an input field as an object to a NodeJs controller using native ajax POST method. I am utilizing the body-parser package on Nodejs to access the POST request. However, when I log the res.body, it appears to be empty. As ...

What steps should be taken to make mocha utilize the HTTP response?

Every time I make an http call, the function it returns causes my comparison to fail because [Function] is never equal to the value I want. Is there a way to make my assert statement consider the true/false flag within it? # test/helloWorld.js const othe ...

Striking a line through the hyperlink tag

I am attempting to create a crossed-out line above the content of an a tag for decorative purposes. The line should stretch across the entire width without intersecting with the actual text within the tag. This is my desired outcome: https://i.sstatic.ne ...

Node.js cluster - Ensuring client session consistency within a single worker

Is there a way to modify the worker assignment strategy in a node.js cluster? For example, can we assign a worker to a client upon their first access and then keep that client on the same worker based on their session ID? In my setup, I am using memory ca ...

Changing the position of the scroll bar in a side navigation bar using JS/jQuery

On my website, there is a side navigation bar with the following CSS style: .scroll-box { overflow: hidden; width: 128px; } .filler { height: 256px; overflow-y: auto; } .selector { background-color: #369; padding: 8px 4px; text-align: cent ...

A guide on updating CSS content dynamically within ExtJS

In my resource folder, I have a CSS file that contains some values which I need to change or add based on certain conditions. However, I'm struggling to figure out how to achieve this. Here is an example of the code: triggers: { clear: { ...

Node.js bug: unexpected behavior when storing a function's return value as a variable

Not much to say right now... I've been utilizing node.js as a WebSocket server, and I've encountered this dilemma?: see image description here (the expected output is: 'works here') These are the lines of code causing this issue: see ...

Save only stack errors to a file in the ExpressJS framework (nodejs)

I am looking to create a dedicated error log file to track only errors that could potentially crash the system. Currently, I am using Morgan to log HTTP requests to a file with the following code: // create a write stream (in append mode) var accessLogSt ...