Is there a way I can set a variable as global in a jade template?

I am trying to pass a global object to a jade template so that I can use it for various purposes later on.

For instance:

app.get("/", function(req, res){

    var options = {
        myGlobal : {// This is the object I want to be global
            "property1" : 1,
            "property2" : 2,
            "property3" : 3,
        }
    };

    jade.renderFile(__dirname +'/tpl/main.jade', options, function (err, html) {
        console.log(err, html);
        if (err)
        {
            throw err
        }
        else
        {
            res.send(html);
        }
    });
});

I would like to have access to "myGlobal" in other scripts that are loaded as if it was defined in the global scope.

Thank you

Answer №1

When utilizing jade as a view engine with express, you can set it up like so:

app.set('views', __dirname); // where your views are located.
app.set('view engine', 'jade');

To define local variables, use res.locals.variable.

For example:

app.get("/", function(req, res){

    res.locals.options = {
        chGlobal : {// object to be accessed globally
            "property1" : 1,
            "property2" : 2,
            "property3" : 3,
        }
    };

    res.render('main');
});

In your Jade template, you can now access the options variable.

You can create a middleware function for automatically adding global variables:

app.get("/", registerGlobals, function(req, res) {

The middleware function would look like this:

function registerGlobals(req, res, next) {
    res.locals.options = {
        chGlobal : {// object accessible globally
            "property1" : 1,
            "property2" : 2,
            "property3" : 3,
        }
    };

    next();
}

For more tutorials on using jade, visit:

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

Disabling a specific tab in an array of tabs using Angular and Typescript

Displayed below are 5 tabs that can be clicked by the user. My goal is to disable tabs 2 and 3, meaning that the tab names will still be visible but users will not be able to click on them. I attempted to set the tabs to active: false in the TypeScript fi ...

Copy files using grunt, in accordance with the ant pattern, while excluding any variable directories

My task is to transfer files from the src/ folder to the dist/plugin directory. Since the version can potentially change, I would like to exclude the version number in all instances. Here is what I currently have: files[{ cwd: 'src' src ...

Bidirectional data flow in AngularJS Directives

In an effort to create a dynamic form with different "widgets" based on field types and parameters stored in a database, I have been exploring directives for handling layout changes in response to various scenarios. After experimenting with some examples, ...

Displaying information in ejs format

I am currently working on a project to develop a basic webpage that requires the user to input a specific time and then click on submit. Once submitted, I want the relevant data linked to that input to be displayed on the webpage. Upon clicking the submit ...

Travis encounters issues deploying Firebase with a script due to an unsupported environment and the fsevents Darwin error

Currently in the process of upgrading my Travis environment to node 20, where I am running a script that deploys Firebase functions. Below is my .travis.yml file: ... install: bash $HOME/build/ChangEdApps/changed-javascript/backend/shellScripts/travis-scr ...

An effective way to connect the ng-model of a <select> element with ng-options within an ng-repeat loop

My task list consists of: [{ Title: "Title1", Position: "9" },{ Title: "Title2", Position: "1" },{ Title: "Title3", Position: "5" },{ Title: "Title4", Position: "7" }] I am attempting to generate a series of <select> ...

Issue with Ng-Messages not functioning properly due to a custom ng-Include directive lacking a child scope

I have created a custom directive called lobInclude, which is similar to ngInclude but with no isolated scope: .directive("lobInclude", ["$templateRequest", "$compile", function($templateRequest, $compile) { return { restrict: "A", ...

What is the method for choosing an Object that includes an Array within its constructor?

Is there a way to retrieve a specific argument in an Object constructor that is an Array and select an index within the array for a calculation (totaling all items for that customer). I have been attempting to access the price value in the Items Object an ...

I encountered an issue with a missing token in the client side mode that requires a secret error. Can anyone guide me on the steps

I encountered an issue while working on a client project. The error message I received states, "A secret error is missing in client-side mode, please provide a token." Please find the code snippet below: const getstream = require('getstream'); c ...

AngularJS ui-select not responding correctly to selected items

Currently, I am utilizing the ui-select module within AngularJS. <ui-select ng-model="tipData.category" search-enabled="false" name="category" required="required" class="orange-site-color-select custom-select"> <ui-select-match><span clas ...

Tips for preventing a component from updating state prior to data retrieval?

I have a specific scenario where I am working with a page that consists of two components. In this setup, I am retrieving data from the root component and passing it to the child component using the react-redux library. However, I encountered an issue wher ...

What is the origin of function parameters in javascript?

I have implemented the following code: handleOwnerMode = ownerChecked => { this.setState(prev => ({ ownerChecked, showOwner: !prev.showOwner})) // this.setState(prev => ({ ownerChecked: !prev.ownerChecked, showOwner: !prev.showOwner ...

Updating the content with HTML and JavaScript

Hello everyone, I am currently working on a project to change the content of a div using JavaScript for educational purposes. Here is what I have done so far - <div id="navbar"> ... <ul> <li> <text onclick="getWordProcessing() ...

Loading Disqus comments dynamically upon clicking a button within a Next.js application

After noticing a significant decrease in page performance scores due to Disqus comments embedded on Vercel Analytics, I am considering implementing a "Load comments" button instead of loading the actual comments onClick. I have been using the disqus-react ...

When attempting to establish a connection with MongoClient, the function fails gracefully without generating an error

try { if (!conn) { console.log("Attempting to Connect to Atlas"); conn = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, }); console.log("Success ...

Exploring JSON data structures using autocomplete functionalities

Here's the code I'm working with: <s:hidden id="s" value="%{Users}"/> The variable Users contains an array list of User objects. This code is written in Javascript. I want to access Users as JSON for auto-complete functionality: var valu ...

Sorry, we couldn't locate the API route you are looking for

Within my Next.js project resides the file main/app/api/worker-callback/route.ts: import { NextApiResponse } from "next"; import { NextResponse } from "next/server"; type ResponseData = { error?: string }; export async function PO ...

Images with fadeIn-Out effect on a slide restrict the movement of the div

I am currently working on a project where I have a div named "background" containing 4 images (400x300px) that fade in and out in a row every x seconds. The issue I am facing is that these images are displaying on the top-left of the browser, and I am tr ...

Is there a method available for us to successfully deliver an email to the user who has been registered?

I am currently working on the registration page for my React app. One of the requirements is to send a confirmation email to the user's email address once they have registered. The user's account will only be confirmed once they click on the veri ...

Perform simple arithmetic operations between a number and a string using Angular within an HTML context

I'm stuck trying to find a straightforward solution to this problem. The array of objects I have contains two values: team.seed: number, team.placement: string In the team.placement, there are simple strings like 7 to indicate 7th place or something ...