B4J Code Snippet [web]Velocity Template Language (VTL)

This example is based on https://velocity.apache.org/engine/2.3/developer-guide.html#how-velocity-works

Download additional libraries:
velocity-engine-core-2.3.jar
commons-lang3-3.12.0.jar
slf4j-api-2.0.7.jar
slf4j-simple-2.0.7.jar

B4X:
'Non-UI application (console / server application)
#Region Project Attributes
    #CommandLineArgs:
    #MergeLibraries: True
#End Region
#AdditionalJar: commons-lang3-3.12.0
'#AdditionalJar: commons-collections4-4.4
#AdditionalJar: velocity-engine-core-2.3
#AdditionalJar: slf4j-api-2.0.7
#AdditionalJar: slf4j-simple-2.0.7
Sub Process_Globals

End Sub

Sub AppStart (Args() As String)
    Dim Velocity As JavaObject
    Velocity.InitializeStatic("org.apache.velocity.app.Velocity")
    Velocity.RunMethod("init", Null)
 
    Dim Context As JavaObject
    Context.InitializeNewInstance("org.apache.velocity.VelocityContext", Null)
    Context.RunMethod("put", Array("name", "Velocity"))
 
    Dim Template As JavaObject
    Template = Template.InitializeNewInstance("org.apache.velocity.Template", Null)
    Template = Velocity.RunMethod("getTemplate", Array As String("test.vm"))
 
    Dim StringWriter As JavaObject
    StringWriter.InitializeNewInstance("java.io.StringWriter", Null)
    Template.RunMethodJO("merge", Array( Context, StringWriter ) )
 
    Dim Content As String = StringWriter.RunMethod("toString", Null)
    StringWriter.RunMethod("close", Null)
 
    Log(Content)
End Sub
 

Attachments

  • Velocity.zip
    1.3 KB · Views: 183
Last edited:

aeric

Expert
Licensed User
Longtime User
@aeric Using your method where do I put the template file? it can't find it wherever I put it lol.
I thought you are feeling adventurous. Why so fast defeated by your Diablo monsters? ?
Sometimes you need some luck and I have given you hint in my screen.
If you have noticed, I use File.DirInternal in B4A. Copy the file from assets to DirInternal. You need the exact path where I use File.Combine to load the file.

Here is the demo for B4J and B4A.
 

Attachments

  • WebviewVTL.zip
    16.5 KB · Views: 146

Daestrum

Expert
Licensed User
Longtime User
Was having too much fun to play Diablo :)

Just working on using strings for the templates, so they can be dynamically created at run time.
 

Daestrum

Expert
Licensed User
Longtime User
Did you try that VelocityLib as a library? saves having all those #additionalJar lines.
 

Daestrum

Expert
Licensed User
Longtime User
Calling subs in your app is quite easy

1, pass a reference to the template
2, call the sub from the template

B4X:
in app

vtl.putContext("caller",Me)

' the sub we want to call from the template
Sub justATest( S As String)
      log(S)
End Sub

in template

$caller._justatest("Hello")
 

aeric

Expert
Licensed User
Longtime User
I tried once and having an error. Will try again later.
I create a new thread for the libraries

 
Last edited:
Top