Reputation: 89
As stated in the docs for interpolation:
- var title = "On Dogs: Man's Best Friend"; - var author = "enlore"; - var theGreat = "<span>escape!</span>"; h1= title p Written with love by #{author} p This will be safe: #{theGreat}
title
follows the basic pattern for evaluating a template local, but the code in between#{
and}
is evaluated, escaped, and the result buffered into the output of the template being rendered.This can be any valid Javascript expression, so you can do whatever feels good.
However, the buffered code in h1= title
is still "evaluated, escaped, buffered...", and "supports the full range of JavaScript expressions" as stated here.
So what is the difference? I can't figure it out.
Upvotes: 1
Views: 448
Reputation: 8540
From Buffered Code section in the docs:
Buffered code starts with
=
. It evaluates the JavaScript expression and outputs the result. For security, buffered code is first HTML escaped.
From String Interpolation, Escaped section in the docs:
The code in between
#{
and}
is evaluated, escaped, and the result buffered into the output of the template being rendered.This can be any valid Javascript expression, so you can do whatever feels good.
So, they both:
I.e. they both do the same things. Which one to use then? My gut says:
Example:
// Normal JS variables
- const name = 'John'
- const greeting = `Hello ${name}!`
// Buffered code
p= greeting // 1
p= 'Hello ' + name + '!' // 2
p= `Hello ${name}!` // 3
// Interpolation
p Hello #{name}! // 4
p #{greeting} // 5
p #{'Hello ' + name + '!'} // 6
p #{`Hello ${name}!`} // 7
// Output in all cases:
<p>Hello John!</p>
Notice that numbers 3 and 7 use template literals. Not to be confused with Pug's string interpolation (numbers 4–7).
In my opinion:
#{
and }
, so you might as well use buffered code for clarity. (But you might prefer them, and that's fine. This is a matter of personal preference.)Upvotes: 1