Fundamental template syntax

1. Pass Entity Objects to Templates

1.1 PageInfo Entity Class

Previously we passed simple strings, which is inefficient and hard‑to‑maintain. Wrapping data into entity objects makes code much clearer.

public class PageInfo
{
    private bool IsShowImage;
    public bool IsShowImage1
    {
        get { return IsShowImage; }
        set { IsShowImage = value; }
    }
}Code language: C# (cs)
  • Private field IsShowImage, exposed via public property IsShowImage1
  • Template access syntax: $info.IsShowImage1

1.2 Populate Context Data

//Template context container
IContext context = new VelocityContext();

PageInfo pi = new PageInfo();
pi.IsShowImage1 = true;

//Store object pi under key name info into context
context.Put("info",pi);

//String variable sample
context.Put("infotitle","Hello");Code language: C# (cs)

context.Put("keyName",data): pass data to template, template reads values by $keyName.

2. Core Velocity Template Syntax

2.1 Directive Marker #

Statements starting with # are directives, common ones:
#if, #else, #end, #foreach, #set, #include

Conditional rendering example:

Prepare two image files and place them under Contents/Images in website root directory. Toggle IsShowImage1 to render different images.

#if($info.IsShowImage1)
    <img src="./Contents/Images/a.gif" />
#else
    <img src="./Contents/Images/b.gif" />
#endCode language: PHP (php)

Logic: render a.gif when IsShowImage1=true, otherwise render b.gif

2.2 Variable Marker $

  • $variableName: output variable value
  • ${variableName}: variable boundary delimiter (critical!)

Scenario: text directly follows variable, engine cannot tell where variable name ends.

Incorrect: $infotitlefoxdevelop.com
Engine parses whole string as variable infotitlefoxdevelop, which does not exist!

Correct: ${infotitle}foxdevelop.com
Engine resolves infotitle variable then concatenate foxdevelop.com stringCode language: PHP (php)

2.3 Silent‑output Modifier !$!variableName

Default: if variable missing, page outputs raw text $variableName
$!variableName: output blank when variable missing or null, do not print dollar sign

Comparison example:

SyntaxVariable exists(value=”Hello”)Variable missing
$infotitleHello$infotitle
$!infotitleHello(blank, nothing rendered)
${infotitle}Hello${infotitle}
$!{infotitle}Helloblank

Full test snippet:

${infotitle}foxdevelop.com <br/>
$!infotitlefoxdevelop.com <br/>
$infotitle <br/>
$!infotitle <br/>Code language: HTML, XML (xml)

Summary

  1. Always wrap variable with ${variable} when concatenating text after variable
  2. Prefer $!{variableName} in production environment, avoid raw $xxx breaking layout on null variables
  3. For boolean property check with #if, write directly #if($info.IsShowImage1), no need extra ==true

Fundamental template syntax

Leave a Reply

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