0
<script>    
    var count_security = 0;
    #set($count_security = 0)  

    function increment() {    
        count_security++;
        #set($count_security = $count_security + 1)
        alert(count_security);
        alert($count_security);    
    }
</script>

<html>
    <input type="button" onclick="increment" />
</html>

When I call the above function on click of the button the "$count_security" variable is incrementing only once. Its not incrementing further.

Please help if I am doing something wrong.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
kishore
  • 35
  • 1
  • 5

1 Answers1

1

This is because of you have two contexts to consider

  • The rendering context (Velocity/VTL)
  • The execution context (Browser/Client)

So when this renders you will have 1 execution in the Velocity engine which will execute the velocity logic that increments $count_security. This will be rendered as a literal value into the output.

the var count_security is a JavaScript CLIENT variable which can be altered and updated by the client.

Your velocity #set() code will not be rendered into the output as a "set". #set is a VTL function and does not alter the output stream.

I hope that makes sense.

Dave G
  • 9,639
  • 36
  • 41
  • or is there a way i can assign a javascript variable to a velocity variable?? – kishore May 11 '11 at 11:41
  • Once the page has rendered through the velocity context any variables associated with that context "evaporate". The context essentially from the standpoint of the client doesn't exist. If you're looking to maintain the count_security on both sides of the fence you're going to need to implement something to keep count_security in the session for the user, and use AJAX to perform an update of that variable in the session to keep it in sync with the client. While this sounds difficult it is a trivial thing to accomplish. – Dave G May 11 '11 at 12:47