Define variables inside templates

The variables covered so far are defined in C# code‑behind files and then consumed in templates. In fact, you can define variables directly inside templates using the set directive.

1. Defining Variables with #set()

Two ways to declare variables:
Method 1: Define variables in advance via backend C#/Java code, read them in template pages;
Method 2: Define variables directly inside templates with #set() (core content of this lesson)

#set($name = "hello foxdevelop.com")
#set($okay = "common baby")
#set($nameokay = "$name|$okay")Code language: PHP (php)
  • #set(variable = value) supports strings, numbers, arrays, object properties and assignments from other variables
  • Weak‑typed, no need to declare variable types

2. Two Variable‑Rendering Syntax and Specifications

2.1 Basic Forms

  • $name: If the variable does not exist, outputs literal text $name
  • $!name: Silent rendering; outputs blank content when variable is missing (recommended to avoid stray $xxx text on pages)
  • Recommended standard syntax: ${name} (curly braces mark variable boundaries explicitly)

2.2 Boundary Issue Example

#set($name = "hello")
$namehello     × Engine parses variable as $namehello and cannot resolve it
${name}hello   √ Correct: resolves $name then appends plain‑text helloCode language: PHP (php)

3. Single‑Line Comments ##

## This is a comment and will never appear in rendered output
#set($name = "test") ## End‑of‑line comments are also supportedCode language: PHP (php)
  1. Comment content will not be printed into the final rendered page;
  2. You cannot see comment text when viewing browser page source (comments get discarded during template‑engine processing).

4. Multiple Assignment Types Supported by #set

## String assignment
#set($name = "hello world")

## Assign one variable to another
#set($obj= $name)

## Assign object properties
#set($obj.Friend = "monica")
#set($obj.Blame = $whitehouse.Leak)

## Call methods and assign return values
#set($obj.Plan = $spindoctor.weave($web))

## Numeric assignment
#set($obj.Number = 123)

## Array assignment
#set($obj.Say = ["Not", $my, "fault"])Code language: PHP (php)

5. Special Rules for Non‑existent Variables

$sadfsdfsdCode language: PHP (php)

When the template engine cannot resolve a variable:

  • Ordinary syntax $sadfsdfsd: outputs literal string $sadfsdfsd
  • Using $!sadfsdfsd: outputs empty string for missing variables

Define variables inside templates

Leave a Reply

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