Passing a function into an EJS template for use in an onclick event?
17,667
Solution 1
- You should put your
js
function in the.ejs
file instead of the server file. - You should pass the function name instead of the entire function code.
app.js
var html = template.render({ clickHandler:"func1();" })
EJS
<p onclick='<%= clickHandler %>'>Click Me</p>
<script>
function func1(){
console.log("I am in the click handler 1!");
}
function func2(){
console.log("I am in the click handler 2!");
}
</script>
Solution 2
You can pass arguments like below
< p onclick="clickHandler('<%= obj.key %>')">Click Me< /p>
Author by
Admin
Updated on June 13, 2022Comments
-
Admin almost 2 years
I'm trying to pass a function into an EJS template and have it be set to an onclick event in the template. Is this possible?
In other words, something like this
var clickHandler = function() { console.log("I am in the click handler!"); } var template = new EJS({ url: "/template.ejs" }); var html = template.render({ clickHandler: clickHandler }) $("#target").html(html);
Where the template looks something like
<p onclick='clickHandler'>Click Me</p>
-
Sherwin Ablaña Dapito almost 5 yearsNow, how can I pass parameter by doing this?