H. Riantsoa
H. Riantsoa

Reputation: 89

In Pug Interpolation, what's the real difference between using buffered code and using #{..}?

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

Answers (1)

Matias Kinnunen
Matias Kinnunen

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:

  1. evaluate a JavaScript expression,
  2. escape it,
  3. output it / buffer it into the output.

I.e. they both do the same things. Which one to use then? My gut says:

  • Use buffered code if the whole line is a JavaScript expression.
  • Use string interpolation if only a part of a line is a JavaScript expression.

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:

  • Numbers 1, 3 and 4 are the best options.
  • Number 2 is OK, but using a template literal would be nicer (number 3).
  • Numbers 5–7 are valid, but maybe a bit unnecessary – the lines don't contain anything else than the JS expressions inside the #{ 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

Related Questions