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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
In my case I was running Pug on the server-side, but you could also use Pug on the client if you want to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.