Extension methods

1. Backend Person Entity Code (C#)

public class Person
{
    private string name;
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    private int age;
    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    //Parameter‑less constructor
    public Person(){}
    //Parameterized constructor
    public Person(string name, int age)
    {
        this.name = name;
        this.age = age;
    }

    //Parameter‑less instance method
    public string getMyName()
    {
        return this.name;
    }

    //Multi‑parameter instance method
    public string JoinStr(string str1, string str2)
    {
        return str1 + str2;
    }
}Code language: C# (cs)

Set object variables in C# backend code

Person pTest = new Person("Tom", 22);
context.Put("pTest", pTest);Code language: JavaScript (javascript)

2. VTL Template Code & Rendering Notes

Method call<br />
$pTest.getMyName();

#set($a = "hello")
#set($b = "foxdevelop")

$pTest.JoinStr($a, $b);Code language: PHP (php)
1. $pTest.getMyName()
  • Call object parameter‑less method getMyName()
  • Return Tom

✅ Velocity parameter‑less method call: parentheses () can be omitted, $pTest.getMyName is equivalent to $pTest.getMyName()

2. $pTest.JoinStr($a, $b)
  • Invoke method with two string parameters
  • VTL parses $a, $b first, pass actual arguments "hello", "foxdevelop"
  • Return concatenated result: hellofoxdevelop

Summary

  1. Method name is case‑sensitive
    C# getMyName()GetMyName(), template must match source code casing.
  2. Pass variables directly
    No extra quotes needed, $pTest.JoinStr($a,$b) is correct; do not write $pTest.JoinStr("$a","$b") (will pass literal string “$a”)
  3. Difference between properties and methods
  • $pTest.Name → access property (getter)
  • $pTest.getMyName() → invoke method
  1. Return values output automatically
    Directly write $object.method() inside template, Velocity prints return value automatically; use #set to capture result if output is unwanted:
#set($result = $pTest.JoinStr($a,$b))Code language: PHP (php)

3. Final Page Render Output

Method call
Tom;

hellofoxdevelop;

Extension methods

Leave a Reply

Your email address will not be published. Required fields are marked *