Demo code here :
All i want is to call a js function and pass a param,
I have tried the following answer, but not works
- How to pass value to a onclick function in (Jade)pug?
And as discussed in the Pug Github issues below,
- Pass Object from Jade to function
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 ?
Demo code here : https://codepen.io/iShawnWang/pen/ZvBGRv
All i want is to call a js function and pass a param,
I have tried the following answer, but not works
- How to pass value to a onclick function in (Jade)pug?
And as discussed in the Pug Github issues below,
- Pass Object from Jade to function
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 ?
Share Improve this question asked Dec 23, 2017 at 12:28 Shawn WangShawn Wang 2,8221 gold badge18 silver badges19 bronze badges2 Answers
Reset to default 4I solved it by myself : https://github./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
So what is the best practice to add onclick listener on Pug template ?
From my own experiences, I remend 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 mon 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 e from anywhere, really"
div(onclick='myFunction(' + '"' + someVar + '"' + ',' + '"' + someVar + '"' + ')')
The linked question now covers this in an answer.