1

I have installed xwiki successfully and able to generate wiki pages using velocity template language.

Could anyone please tell me that how can I pass javascript varible to velocity templete. I have gone through few forums that I need to pass the parameter to server to get this but I have no idea. Please find the files below.

<script type="text/javascript">
function generateFunction()
{
  var variable = document.getElementById('text').value;
}
</script> 

#set($test = "variable")
$test
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
charan098
  • 11
  • 1
  • 4

2 Answers2

2

You have to make an ajax call from the client to the server.If you're using jquery, you would have something like:

$.post('/send/my/var', { 'variable' : value });

Without jquery, see this XmlHttpRequest documentation.

And then, on the server side, the /send/my/var URL should reach a template where you can do:

#set($test = $params.variable)

And you would do something useful with it on the server-side, like store it in the session, in the database, etc.

If you need to send back something from Velocity to Javascript, then you'll typically have to format JSON code, and add an asynchronous completion callback parameter to the ajax call:

$.post('/send/my/var', { 'variable' : value }, 
  function(data)
  {
     // do something with data sent back from the server
  });

It's also possible to have synchronous calls, that is to have javascript wait for the server response, but it's generally a bad idea to do so and I won't extrapolate on it here.

As a final note, you should also implement a proper error handling. With jQuery for instance, the syntax would be:

$(document).ajaxError(function(event, jqxhr, settings, message)
{
    console.log(message);
});
Claude Brisson
  • 4,085
  • 1
  • 22
  • 30
1

It can't be done,

Apache Velocity template is a server side engine,

Meaning that on the server, Velocity will get the template and try to render, only after it finished to render the template, it will be returned to client which will execute client code as Javascript

Velocity alternative is freemarker, which I found similar question and answer , Question:

How to call freemarker function with param from javascript

Answer:

There's no way for the client side web browser code to call a server side Freemarker function

Community
  • 1
  • 1
Ori Marko
  • 56,308
  • 23
  • 131
  • 233