0

I have a pug template where I want to call a function with some variables passed from the endpoint that renders the page:

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    button(type = 'button' onclick='play(#{x},#{y})')
    script(type='text/javascript' src='../public/javascripts/play.js')

Here is play.js:

const play = function(x,y){
    console.log(x+y);
}

When I load the page, I get this error:

Uncaught SyntaxError: Unexpected token ':'     play.js:1

How can I get pug to include the script correctly so that I can call the function with a button click?

EDIT: here's the rendered HTML:

<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<button type="button" onclick="play(#{x},#{y})"></button><script type="text/javascript" src="../public/javascripts/play.js"></script>
</body>
</html>

EDIT 2:

I changed the interpolation to

onclick=`play(${x},${y})`

and this renders as:

onclick="play(2,3)"

which are the values that were passed in from the endpoint, but I'm still getting the unexpected token error.

sigil
  • 9,370
  • 40
  • 119
  • 199
  • What does the rendered HTML look like (use _View page source_ in your browser)? – Phil Nov 19 '21 at 06:01
  • @phil just added it to the OP – sigil Nov 19 '21 at 06:09
  • Doesn't look like your `x` and `y` vars are interpolating correctly – Phil Nov 19 '21 at 06:11
  • See https://pugjs.org/language/attributes.html#attribute-interpolation – Phil Nov 19 '21 at 06:13
  • @phil fixed the interpolation but still getting the same `unexpected token` error – sigil Nov 19 '21 at 06:32
  • I ran the code in your question in my own app (but with path to play.js set to my location of play.js) and everything ran fine. `Unexpected token` is usually a parsing error by pug, ie something that breaks pug syntax. A `'` or `"` in your variables `x` or `y` would cause that. Do you have any non-visible characters in your code? – Old Geezer Nov 19 '21 at 14:26
  • 1
    I am curious why the `src` path to your play.js is `../public/javascript`. Your stylesheet reference suggests you have a folder set up for static files. If that is correct, then it should be `src='/javascript/play.js'`. Whatever it is, the contents of play.js shouldn't cause that error as it is loaded by the client, long after pug has finished processing on the server. – Old Geezer Nov 19 '21 at 14:28
  • @OldGeezer your diagnosis of the path issue turned out to be correct. However, I still can't attach the event listener, and I'm going to post a new question with updated code. – sigil Nov 19 '21 at 19:04
  • @OldGeezer if you're curious, the new question is [here](https://stackoverflow.com/questions/70040543/parameters-in-pug-template-not-available-for-onclick-event) – sigil Nov 19 '21 at 20:23

0 Answers0