How to add JavaScript functions to a Pug template
Asked Answered
P

1

7

There are many issues with adding JavaScipt to Pug templates including:

  • PugJS throws exceptions on many JavaScript functions that are perfectly valid.
  • When your JavaScript functions have syntax errors they are not identified for you.
  • You can't set a breakpoint in a JavaScript function within a Pug template
  • You can't use Typescript to help with robustness

What is the preferred/recommended way to use JavaSript functions with Pug?

Pediatrician answered 16/7, 2020 at 17:36 Comment(0)
P
10

I struggled with these issues for a while before realizing that there is a much better option. I recommend passing JavaScript functions to the Pug render function instead of building them into the template.

What I was doing before was this JavaScript

const render = pug.compileFile(path.join(__dirname, '../templates/sandbox.pug'));
const html = render({});

and this Pug template

- var testFunc = function(){
-     return "Test func";
-   }

div #{testFunc()} worked!

The better way of achieving the same thing is with this JavaScript

const render = pug.compileFile(path.join(__dirname, '../templates/sandbox.pug'));
const html = render({
  testFunc: function(){
    return "Test func";
  }
});

and this Pug template

div #{testFunc()} worked!

This allows you to set breakpoints, use Typescript and all the other cool stuff, and avoids all of the Pug bugs related to parsing JavaScript not very well.

Pediatrician answered 16/7, 2020 at 17:36 Comment(2)
Am I right that the original javascript code would run on the client, while the 'better way' code would run on the server? Not good if the code should manipulate the DOM.Ethylethylate
In my case I was running Pug on the server-side, but you could also use Pug on the client if you want to.Pediatrician

© 2022 - 2024 — McMap. All rights reserved.