Reputation: 2742
All i want is to call a js function and pass a param,
I have tried the following answer, but not works
And as discussed in the Pug Github issues below,
Event handlers like onclick can only be added through HTML or client-side JavaScript. This is not something Jade can help you with.
So what is the best practice to add onclick listener on Pug template ?
Upvotes: 2
Views: 7707
Reputation: 2742
I solved it by myself : https://github.com/pugjs/pug/issues/2933
a.postTitle(onclick=`viewPost(${JSON.stringify(file)})`)= file.name
then, I can receive an object at viewPost
function,
take care of the ` symbol
Upvotes: 4
Reputation: 132
So what is the best practice to add onclick listener on Pug template ?
From my own experiences, I recommend adding script
tag with the event handler logic to the template, and declaring the onclick
without any backticks, grave-accents, string-interpolation marks:
`
String interpolation marks will fail with some UglifyJs build steps (usually common in Prod configurations):
this-will-${fail}-in-some-UglifyJs-versions
An example of what I mean would look like this:
// my template.pug
script
function myFunction(varA, varB){
// do something...
}
- var someVar = "this is a string, but the value could come from anywhere, really"
div(onclick='myFunction(' + '"' + someVar + '"' + ',' + '"' + someVar + '"' + ')')
The linked question now covers this in an answer.
Upvotes: 0