B4J Library [B4X] Velocity

A wrap of Apache Velocity Engine library for B4A and B4J

What is Velocity?​

Velocity is a Java-based template engine. It permits anyone to use a simple yet powerful template language to reference objects defined in Java code.
Source: https://velocity.apache.org/

Download additional libraries:
velocity-engine-core-2.3.jar
commons-lang3-3.12.0.jar
slf4j-api-2.0.7.jar (required if not using jServer)
slf4j-simple-2.0.7.jar (required if not using jServer)

Based on this original code snippet: Velocity Template Language (VTL)

Change Logs:
v1.01 - Changed to b4xlib. Modified Initialize method.
v1.02 - Added evaluate method. Added example project.
v1.03 - Renamed Text method to ToString. Removed redundant references for slf4j libraries in manifest.txt which already existed in jServer.


Velocity
Author:
aeric, Daestrum
Version: 1.03
  • Methods:
    • Initialize (Directory As String)
      Initializes the object. You can pass a default directory inside Objects directory
    • put (Key As Object, Value As Object)
      Put Context with Key Value pair
    • putMap (m As Map)
      Put Context by passing a Map
    • merge
      Merge Template with Context and pass to StringWriter
    • mergeTemplate (TemplateFile As String, Encoding As String)
      Merge a Template with Context and pass to StringWriter
    • evaluate (Tag As String, TemplateString As String)
      Evaluate TemplateString
  • Properties:
    • get (Key As String) As Object [read only]
      Get the Context by Key
    • Template As String [write only]
      Load a Template file
    • ToString As Object [read only]
      Return StringWriter as String
(generated from http://b4a.martinpearman.co.uk/xml2bb/ and edited)
 

Attachments

  • Velocity.b4xlib
    1.2 KB · Views: 189
  • VelocityExample.zip
    14.8 KB · Views: 212
Last edited:

aeric

Expert
Licensed User
Longtime User
Tips:
You can load more than one template files.

B4X:
Velocity.mergeTemplate("mainLayout.vm", "UTF-8")
Velocity.mergeTemplate("index.vm", "UTF-8")

You can use the $!bodyContent variable.

mainLayout.vm:
HTML:
#macro(mainLayout)
<head>
    ...
</head>

<body>
    $!bodyContent
</body>
#end

index.vm:
HTML:
#@mainLayout()
  <h1>Index page</h1>
#end
 

aeric

Expert
Licensed User
Longtime User
Update v1.03
- Renamed Text property to ToString.
- Removed redundant references for slf4j libraries in manifest.txt which already existed in jServer.

If not building jServer app, add the following to the Main module:
B4X:
#AdditionalJar: slf4j-api-2.0.7
#AdditionalJar: slf4j-simple-2.0.7
Check the updated example in post #1.
 
Last edited:
Top