How do I interpolate variable string in pug?
Asked Answered
A

3

8

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

Abstraction answered 25/10, 2016 at 10:4 Comment(2)
I suggest re-writing your question and try to explain better what you are trying to do because it doesn't make much sense. Put some real examples, and show what you have attempted so far. Do you mean myVar is a string, and part of that string is "${date}"? And if so, are you asking how to replace that? (if so, then you need to go and research "javascript replace in string"Selfstarter
Sorry. I made it more clear.Abstraction
B
12

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!

Brunildabruning answered 3/10, 2018 at 9:10 Comment(0)
I
6

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}`;
Immediacy answered 21/10, 2019 at 19:23 Comment(0)
S
2

Pug interpolates with a hash. #{interpolation}

Sadiron answered 4/11, 2016 at 16:39 Comment(1)
and with default value - #{interpolation || DEFAULT_VALUE}Mangle

© 2022 - 2024 — McMap. All rights reserved.