The Java 8 release included a JavaScript engine called Nashorn. Nashorn allows us to run dynamic JavaScript code natively on the JVM.
...
Code Block |
---|
language | yaml |
---|
title | add this to your webapp pom |
---|
|
<dependency>
<groupId>info.magnolia.javascript-models</groupId>
<artifactId>magnolia-module-javascript-models</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency> |
If you are using M 5.6.*, try this instead:
Code Block |
---|
<dependency>
<groupId>info.magnolia.javascript-models</groupId>
<artifactId>magnolia-module-javascript-models</artifactId>
<version>1.1.1</version>
</dependency> |
If your bundle doesn't already include it, and if you are unable to include this, the jar file is attached: magnolia-module-javascript-models-1.0.jar Simply drop it in your author instance WEB-INF/lib and restart Magnolia. Otherwise, you could download it from here.
Code Block |
---|
language | yaml |
---|
title | new-module/templates/components/contacts.yaml |
---|
|
templateScript: /new-module/templates/components/contacts.ftl
renderType: freemarker
modelClass: info.magnolia.module.jsmodels.rendering.JavascriptRenderingModel |
Code Block |
---|
language | yaml |
---|
title | new-module/templates/components/contacts.ftl |
---|
|
[#assign allContacts = model.getContacts()]
<ul>
[#list allContacts as contact]
<li>${model.format(contact)}</li>
[/#list]
</ul> |
Code Block |
---|
language | js |
---|
title | new-module/templates/components/contacts.js |
---|
|
var MyModel = function () {
this.getContacts = function () {
var result = new Array();
var nodes = ctx.getJCRSession("contacts").getRootNode().getNodes();
while (nodes.hasNext()) {
node = nodes.next();
if (node.getPrimaryNodeType().getName() == 'mgnl:contact') {
result.push(node);
}
}
return result;
};
this.format = function (contact) {
return contact.getProperty("firstName").getString() + ' ' + contact.getProperty("lastName").getString();
};
};
new MyModel(); |
Code Block |
---|
language | yaml |
---|
title | add this to the availableComponents of some area definition |
---|
|
contacts:
id: new-module:components/contacts |
The result
Nashorn - Pros and Cons
...
Some more examples may be found here.