3

I am building a website using Spark + Velocity. This has HTML components that are very similar across the webpages of the site, so I have put my shared components in some templates that I dynamically load into the page.

To give you a simple example, I have pages such as this:

anyPage.vm

<head> stuff in here </head>
<body>
<div id="header"></div>
$AJavaObject.ToString() # <-- using the Velocity templating language
...
</body>
<script type="text/javascript">
    $(function(){
         $("#header").load("header.vm");
    }
</script>

This works all right, except for the fact that the Velocity code inside header.vm won't work.

header.vm

<h1>Header</h1>
$AnotherJavaObject.toString()

The header.vm does not contain any <head> or <body> tagging.

When rendering the page, instead of seeing the string representation of the AnotherJavaObject, I see the actual string $AnotherJavaObject.toString().

Any help is appreciated. Thanks.

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
crazyGuy
  • 338
  • 2
  • 15

2 Answers2

3

SOLVED

For anyone facing this same issue, the solution is within the Velocity Template Engine itself: http://velocity.apache.org/engine/1.7/user-guide.html#parse

Instead of calling load() on the component with the header id, you just need to have

#parse("header.vm")

where you want the header.vm to be rendered.

You should use the #include directive to load static, non-Velocity templates like:

#include("other.html")

This is not this simple however. The documentation states that #parse and #include can only load resources from the TEMPLATE_ROOT. I was unable, however, to find out what that root is. So, on initialising the Velocity Engine, I had to enable this to accept relative paths:

properties.setProperty(RuntimeConstants.EVENTHANDLER_INCLUDE, IncludeRelativePath.class.getName());
velocityEngine = new org.apache.velocity.app.VelocityEngine(properties);
crazyGuy
  • 338
  • 2
  • 15
1

You can't load it in JavaScript after template return results. you should use parse see Velocity Loading resources:

#parse("header.vm")

And if you need to hide it use JavaScript to display/hide the results.

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