Verifying the URL to determine if it includes the specific string needed to modify the Jade theme in

I am currently exploring ways to check if a URL string is present in an express application, in order to initiate a theme change.

At the moment, I have a basic router.get function:

router.get('/', function(req, res, next) {

  res.render('index', { title: 'Home' });
});

My goal is to check the URL for a specific string, such as "Toy", and based on that, somehow trigger jade/pug to display a different graphic.

store.org 
trigger main Graphic

toystore.org
trigger a different graphic 

Then, I need to pass this information so that I can adjust the theme in pug/jade. What are your thoughts on this approach?

I was considering using string.match along with regex to search for the desired trigger, but that may not work as I need to modify it to change the theme in pug/jade.

Answer №1

In order to adjust a view based on certain conditions of the request, follow these steps:

  • Firstly, check the condition in a middleware and add a custom property to the request or response object

  • Then, utilize this custom property later on

In your app.js, preferably above the routes section:

const evaluateTheme = (req, res, next) => {
    if(req.hostname === "store.org" {
        res.locals.theme = "graphic"
    } else {
        res.locals.theme = "other-graphic"
    }
    next();
};

app.use(evaluateTheme);

Afterwards, simply access the value stored in res.locals.theme when needed.

EDIT: In response to your inquiry about "displaying different graphics", providing a solution without specific details can be challenging.

If you wish to showcase distinct page elements, consider creating two separate pages and selecting which one to display within your controller logic:

const pickIndexBasedOnUrl = (req, res, next) => {
    if(res.locals.theme === 'graphic') {
        res.render('index/graphic');
    } else {
        res.render('index/other-graphic');
    }
};

For minor adjustments, evaluate the theme inside your view file and apply changes using an if condition:

if theme === 'graphic'
    h2.green Description
else 
    h2.red Description

You could even incorporate conditional statements to import varying CSS files.

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

Implementing a UserID field that automatically increments with each new entry

I am in the process of developing an API to extract and insert data from a database using the MEAN stack. My goal is to have the userID automatically generated, starting from 0, whenever a new entry is created in the userschema. var userSchema = new mong ...

What is the best way to transfer a variable from jQuery to a PHP script?

While I am aware that similar questions have been asked in the past, I am facing a unique challenge in trying to create a table with distinct links and pass the id of the link to a PHP page. Here is what I have so far: echo("<p>To reser ...

Having Trouble Parsing JSON Object with JQuery?

I'm having trouble extracting data from a valid JSON object using jQuery/JavaScript - it always returns as 'undefined'. var json = (the string below). var obj = $.parseJSON(JSON.stringify(JSON.stringify(json))); alert(obj); // aler ...

Refresh a Particular Section of a Website Without Having to Reload the Entire Page

I have this PHP script that I'm using to read specific phrases from a text file and then display one of them randomly on a webpage. Currently, the only way to see a new random phrase is by refreshing the entire page. I'm wondering if there is a w ...

Guide on importing CDN Vue into a vanilla Typescript file without using Vue CLI?

In the midst of a large project that is mostly developed, I find myself needing to integrate Vue.js for specific small sections of the application. To achieve this, I have opted to import Vue.js using a CDN version and a <script> </script> tag ...

Is it possible to retrieve a JSON property using a string?

Here is the JSON I am working with: json_filter = {"CO": "blah"} I am attempting to access the member 'CO' using a string value, but the result keeps coming back as undefined. var selectedState = $(this).val(); // The state selected is 'C ...

Deactivating checkboxes once the maximum selection has been made through jquery

I need assistance with my jQuery code that is supposed to disable checkboxes in a multidimensional array after reaching the maximum number of selections. However, I am having trouble identifying the issue within the code. Any guidance would be greatly ap ...

Sending a multitude of variables using strings, evaluating them through various functions, and incorporating a variety of methods

To put it simply, my goal is to utilize an object literal that allows me to pass an unknown quantity of variables in any order to a function. While this may seem straightforward in principle, within my code, this object literal is passed to a second functi ...

The de-duplication feature in webpack is not functioning properly when the splitChunks cacheGroups commons option is activated

In my lerna project, I have two identical packages named p1 and p2. Both p1 and p2 utilize a 3rd party package - in this case, eosjs@beta, which is approximately 50KB in size. When I incorporate p1 into an example react project, the package size increase ...

Assign the ng-repeat item to a variable in the controller's scope

Can anyone help me figure out how to pass a particular item from my view to a function in my controller? Here is the code: The view where I want to pass p.id <tr ng-repeat=" p in projetsListe"> <td>{{p.NomProjet}}</td> <td>{{c ...

What is the best way to connect a series of checkboxes within a form utilizing Angular?

I created a form with checkboxes that allow users to select multiple options. However, when I submit the form, instead of receiving an array of objects representing the checked checkboxes, I'm not getting anything at all. Here is what I see in the co ...

Creating effective test cases for Angular JS controllers

Our team has recently taken on the task of writing test cases for our application, specifically focusing on controllers. Utilizing Mocha, Chai, and Sinon libraries, we are looking for guidance on how to effectively write these test cases. We have shared a ...

A helpful guide on displaying validation errors in a form using React JS

After creating a form and connecting it to the server, I encountered an issue with displaying validation errors below respective input fields. The error message response in case of validation error is as follows: "message": "ValidationError: confirmPasswor ...

Error in AngularJS v1.2.5 when using textarea with placeholder attribute in IE11

Having trouble with an Angular JS v1.2.5 form that is not functioning in IE11, despite working perfectly in Firefox, Chrome, and Safari. The issue seems to be related to using interpolation inside the placeholder attribute of a textarea. <body ng-con ...

Using jQuery in Yii: Detecting when a radio button loses its checked state

Here is the code regarding the issue at hand: <script> $(function(){ $('#widgetId-form input[name="valueType"]').change(function(){ if ($(this).is(":checked")) { console.log("enabling "+$(this).data("class") ...

While executing a jssor code in SP 2007, IE experiences freezing issues

I've integrated a jssor slider with vertical navigation (without jQuery) into a Sharepoint 2007 page using CEWP. All the image links have been replaced with images stored in the SP image library, and the jssor.slider.min.js file has been uploaded to t ...

Improving the Performance of DisplayField Binding in ExtJS 5

When I trigger a window to create a new item, there is a noticeable lag when passing in the record for the bound fields. The record is essentially a blank one with default values provided by the framework. In this demo, there are 3 buttons: The first but ...

The ashx file is triggered with every server control postback in jqgrid

I have an asp .net webforms page with a jqgrid, as well as several other server controls. The jqgrid is populated using an ashx file which retrieves data from the database and binds it successfully. Challenge Whenever a postback occurs (such as from a dro ...

What is preventing the audio from playing in Safari?

Recently, I developed a small JavaScript program that is meant to play the Happy Birthday tune. This program utilizes setInterval to gradually increase a variable, and depending on its value, plays or pauses certain musical notes. However, I encountered ...

Creating a query string using a jQuery array that contains multiple values for a query variable

After writing some code to convert an array into a filter string, I noticed that the generated string was not in the format I wanted. product_size=123&product_size=456 Instead of this, I needed it to be product_size=123+456. To achieve this, I reali ...