简体   繁体   中英

How do I interpolate variable string in 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

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!

Pug interpolates with a hash. #{interpolation}

To render variables directly in a string in a Pug template, you can use the typical ES6 interpolation. Example (assuming pageTitle is in scope, and passed as template context):

 - var pageTitle = `Google | ${pageTitle}`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM