Value Interpolation in JavaScript Code using Pug

Tutorial Difficulty Level    

Interpolating values is helpful if you need to pass a server-side variable to client-side JavaScript (or other languages that require it).

In the case of variables, numbers, strings, and the like, you can pass these types of variables directly into your JavaScript with bracket syntax plus an explanation point (so that the code inside the brackets is not evaluated.) This is useful for parametrizing JavaScript code that require something from your server.

In the below example, we have to wrap username in quotation marks in order for JavaScript to interpret it as a string; Pug will output the content of the variable as-is, so we need to put it in quotation marks for it to be a proper JavaScript string. This is not necessary for number, where JavaScript will interpret our number as it we intend it to (as a number).

If you need to interpolate the value of a JavaScript object (e.g. all the information about a user), you must stringify the output in Pug for it to be treated as a JavaScript object. It’s also necessary to output the raw contents of the variable, instead of the evaluated form of it. If you were to do output the escaped variable (var user = #{JSON.stringify(user)}), you would receive an escapedversion of the object (where quotation marks and apostrophes are converted to "), which is not what we want in order for JSON.stringify to work on it.

The innerHTML of #welcome-user becomes equal to Madeline Smith. The contents of the user variable are printed directly to the HTML source.