Search code examples
freemarker

can we call a ftl macro from javascript function


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> Java, Spring Boot, FreeMarker</title>
    <link href="/css/main.css" rel="stylesheet">
</head>
<script>
function myFunction() {
        <@test/>
}
</script>
<body>
    <h2>Java, Spring Boot, FreeMarker</h2>
     <form action="/search" method="post">
   Search : <input type="text" name="firstName" onkeyup="myFunction()" id = "fname"> 
   <input type="submit" value="Submit">
   </form>
        <div style="background-color:lightblue">
          <#macro test>
            <#list empList as emp>
            <div id="emp-data">
            <ul>
                <li>${emp}</li>
            </ul>
            </#list>
            </div>
        </#macro>
    <script src="/js/main.js"></script>
    </div>

</body>

When I run this code I am getting some errors on the browser console:

(index):60 Uncaught ReferenceError: myFunction is not defined at HTMLInputElement.onkeyup ((index):60) onkeyup @ (index):60 – PCS 1 hour ago

Is it possible in FreeMarker to do something like that?


Solution

  • In a sense you can... but it doesn't do what you apparently believe it does. First all FreeMarker instructions, like <@test/>, are resolved on the server, then later the resulting output runs in the browser. So as far as the browser sees, function myFunction() { ... } contains HTML div-s directly in inside the { ... }, which is invalid JavaScript.