Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating a variable + string in Jade file

I am passing in a session variable from my mongodb session store in an Express for Node.js web app like this:

exports.dashboard = function(req, res){
    res.render('dashboard', {pref: req.session.layoutpref});
}

Then, in my Jade file I'm trying to assign the value of pref to the css link like this, but I'm getting a syntax error:

head
        title #{title}
        link(rel='stylesheet', href='/stylesheets/' + #{pref} + '.css')

I'm almost certain the problem is in my concatenation of pref into the location of the css file to be used. Any ideas how to fix this?

like image 895
gjw80 Avatar asked Oct 15 '13 18:10

gjw80


People also ask

How do I concatenate a variable to a string?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect. let myPet = 'seahorse'; console.

Can variables be combined with strings?

To combine the values of two or more variables or text strings into a single text value, you use the string concatenation function.

How do you concatenate strings and variables in Java?

Using the + operator is the most common way to concatenate two strings in Java. You can provide either a variable, a number, or a String literal (which is always surrounded by double quotes). Be sure to add a space so that when the combined string is printed, its words are separated properly.


2 Answers

use #{} notation if you want to interpolate a variable in the contents of an element. you can just use the variable names straight up if you want to use them in attributes.

link(rel='stylesheet', href='/stylesheets/' + pref + '.css')

equivalent:

link(rel='stylesheet', href='/stylesheets/' + locals.pref + '.css')

when to use #{}:

a(href='/stylesheets/' + locals.pref + '.css') View the stylesheet at #{pref}
like image 126
Plato Avatar answered Oct 19 '22 21:10

Plato


Jade files are compiled in Node.js env.

Node.js (from v4.0.0) supports template literals, so

link(rel='stylesheet', href=`/stylesheets/${pref}.css`)

equivalent:

link(rel='stylesheet', href='/stylesheets/' + pref + '.css')
like image 31
Vitaly Shapovalov Avatar answered Oct 19 '22 20:10

Vitaly Shapovalov