Running Gosu statements in a template scriptlet
Text enclosed with the text <% and %> evaluates at run time in
the order the parser encounters the text but generates no output from
the result. These character sequences are called scriptlet tags. Note
that this type of tag has no equal sign in the opening tag. Scriptlet tags enclose Gosu statements,
not expressions. Gosu evaluates all plain text between scriptlet tags
within the scope and the logic of the scriptlet code.
The scriptlet tags are available in template
files and in String literals
that use template syntax.
The following template uses a scriptlet tag to run code to assign a variable and uses the result later:
<% var MyCalc = 1 + 2 %>One plus two is ${ MyCalc }The result of this template is the following:
One plus two is 3The result of the scriptlet tag at the beginning of the template does not generate any output. The statement inside
the scriptlet tags creates a variable MyCalc, and assigns the result of a calculation to that
variable. The subsequent expression uses the expression delimiters ${ and } to
cause Gosu to retrieve the value of the variable MyCalc, which is 3.
The scope of the Gosu code continues across
scriptlet tags. Use this feature to write advanced logic that uses Gosu
code that you spread across multiple scriptlet tags. For example, the
result of the following template code is “x is 5” if the variable
MyCalc has the value 5,
otherwise the result is “MyCalc is not 5”:
<% if (MyCalc == 5) { %>
MyCalc is 5
<% } else { %>
MyCalc is not 5
<% } %>
The if
statement controls the flow of execution of later elements in the template.
You use this feature to control the export of static text in the template
as well as template expressions.
Scriptlet tags are particularly useful when used with template parameters because you can define conditional logic as shown in the previous example.
Use this syntax to iterate across lists, arrays, and other iterable objects. You can combine this syntax with the expression syntax to generate output from the inner part of your loop. Remember that the scriptlet syntax does not itself support generating output text.
For example, suppose you set a variable
called MyList that contains
a List of objects with
a Name property. The following
template iterates across the list:
<% for (var obj in MyList) {
var theName = obj.Name %>
Name: ${ theName }
<% } %>
This template might generate output such as:
Name: John Smith
Name: Wendy Wheathers
Name: Alice Applegate
The following code shows the use of scriptlets in
a String value:
var str = "<% for (i in 1..5) { var odd = (i % 2 == 1) %>${i} is ${ (odd?"odd":"even") }\n<% } %>"
print(str)
This code prints:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
See also
