How to add JavaScript functions to a Pug template

Viewed 1680

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?

1 Answers

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.

Related