Repeat
Very often you need to display a list of things or the same thing multiple times.
This can be easily achieved with a repeat
statement.
The basic syntax for a repeat
is: repeat(VARIABLE_NAME in EXPRESSION)
Count based repeat
To repeat a fixed number of times, just supply an expression that evaluates to an integer.
template RepeatSample render {
int count = 100;
repeat(i in count) {
Text($"Showing {i}");
}
repeat(i in count / 2) {
Text($"Showing {i}");
}
repeat(i in 400) {
Text($"Showing {i}");
}
}
List based repeat
Usually you have a list of data that you want to repeat over. The basic syntax is the same as a count
based repeat. Additionally you can extrude the current index with [index]
. The list expression
can be anything conforming to IEnumerable
or IList
. Note that IEnumerable
is significantly slower due
to a. possibly boxing a IEnumerator
instance and b. often requiring multiple enumeration to find a count.
Repeating over IList
or Array
instead of IEnumerable
is strongly encouraged!
template RepeatSample render {
int[] items = new int[] { 1, 2, 3 };
repeat(item in items) [index] {
Text($"Showing {item} at {index}");
}
}
Key Functions
Repeat also participates in Structural Identity which generally means that the indices in your list dictate
the scopes their items belong to. Most of the time this fine, but sometimes you need to make that one scope
is always tied to one value in your list. If you have data that will be sorted or mutated, you need to make sure
the same UI elements are representing the same data every frame. You can ensure this by providing a keyFn
argument
to your repeat.
A key function is any function or lambda with the signature int Fn<T>(T item)
where T
is the type of the data in your list.
An example:
// some C# file
public static class Shuffle {
private static Random rnd = new Random();
public static int[] GetArray() {
return Enumerable.Range(0, 10).OrderBy(c => rnd.Next()).ToArray();
}
}
// some .ui file
template KeyFnSample render {
// not a 'state', we get a new array one every time
// but the data is the same random sorting of integers 0-10
int[] ints = Shuffle.GetArray();
// items will stay red by index when clicked on.
repeat(val in ints) {
state bool clicked = false;
Text(style:BackgroundColor = clicked ? `red` : `blue`, mouse:click = clicked = !clicked);
}
// items will stay red by value.
repeat(val in ints, keyFn = (i) => i) { // identity key fn
state bool clicked = false;
Text(style:BackgroundColor = clicked ? `red` : `blue`, mouse:click = clicked = !clicked);
}
}