Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I interpolate variable string in pug?

Tags:

javascript

pug

In the following, myVar contains the string "Today, it's the ${date}". Furthermore, there is an variable with the name date that contains "1st of October". I expect the following pug syntax to replace the literal ${date} with the date variable content.

span!= myVar

Unfortunately, the example results in

<span>Today, it's the ${date}</span>

Expected result:

<span>Today, it's the 1st of October.</span>

Best regards, Benedikt

like image 269
Benedikt Avatar asked Dec 14 '22 02:12

Benedikt


1 Answers

Yes, exactly as @omgninjas pointed out, it is called interpolation and preceded by # in Pug.

However you can't always use it (eg. inside a string). Here are some examples:

sensor is a variable passed by the controller to the view.

  1. Normal interpolation. Works as expected:

<div id=#{sensor} style="width:90%;height:250px;"></div>

  1. Inside a string with Template Literals (don't use these with user supplied values!):

img(src=`/images/${sensor}.png`, style="width:20%")

  1. Inside a string used to denote a function call. Note that you cannot use the ` symbol (back tick aka grave accent used in template literals) with function calls because you would have to ecompass the entire function call . This results in a string which is not going to be executed. You need to use string concatenation.

body(onload="initTemp('"+ sensor +"')")

Here is the official documentation for Pug interpolation: https://pugjs.org/language/interpolation.html

Hope this helps. Corrections and suggestions always welcome!

like image 198
Andrei Avatar answered Dec 17 '22 02:12

Andrei