Skip to content

Dynamic Content Constants and Loops

Mike Christensen edited this page Aug 28, 2026 · 1 revision

Dynamic content, constants, and loops

Imp template commands connect embedded markup to page members.

Dynamic methods

<Dynamic.Name /> calls a public instance method named Name on the page. The required shape is:

public Task Name(TextWriter output, DynamicContentArgs args)

Example:

<p><Dynamic.Greeting Punctuation="!" /></p>
public Task Greeting(TextWriter output, DynamicContentArgs args)
{
   var punctuation = HtmlEncoder.Default.Encode(args["Punctuation"] ?? string.Empty);
   var name = HtmlEncoder.Default.Encode(Name);
   return output.WriteAsync($"Hello, {name}{punctuation}");
}

Attributes are available by exact name through args[name] or GetParameter. They are template-authored strings, but values combined with request/application data still need context-appropriate encoding.

Dynamic methods execute every render. Keep them focused; move business logic into injected services.

Constants

<Const.Name /> writes the raw value of a public literal field on the page type:

public const string ProductName = "Example";
<title><Const.ProductName /></title>

Only literal fields are supported. Constants are inserted during template compilation, not recomputed per request.

Loops

<Loop.Items> calls a public parameterless method returning non-generic IEnumerable, then renders its child commands for every value:

<ul>
  <Loop.Items>
    <li><Dynamic.Item /></li>
  </Loop.Items>
</ul>
public IEnumerable Items() => store.GetAll();

public Task Item(TextWriter output, DynamicContentArgs args)
{
   var item = (TodoItem)args.LoopValue;
   return output.WriteAsync(HtmlEncoder.Default.Encode(item.Title));
}

Inside the loop, DynamicContentArgs.LoopValue contains the current object. Nested static markup and dynamic commands are compiled once and reused for each item.

Loop data sources are synchronous. Materialize asynchronous results before rendering or expose a synchronous application snapshot. Never call .Result on request-time tasks.

Method binding failures

The compiler resolves members by name with reflection. Missing members produce PageMethodNotFoundException or StaticResourceNotFoundException; incompatible signatures fail during delegate binding. These are programmer/configuration errors—fail visibly, log the page/resource, and correct the template and page together.

Clone this wiki locally