Bundle: redb-route / redb.Route.Templates (redb.Route.Templates.txt), 14 files
Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.Templates/MediaType.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/MediaType.cs
----
namespace redb.Route.Templates;
///
/// Result type of a payload template. Decides how substituted values are escaped and which
/// ContentType the produced body gets. Mandatory: without it a value containing a quote or
/// an ampersand silently breaks the document (WSO2 PayloadFactory defaults to XML, which is a trap).
///
public enum MediaType
{
/// JSON: ", \ and control characters in substituted strings are escaped; ContentType = application/json.
Json,
/// XML: &, <, >, ", ' in substituted strings are escaped; ContentType = application/xml.
Xml,
/// Plain text: no escaping; ContentType = text/plain.
Text,
}
Path: redb-route/redb.Route.Templates/PayloadTemplateContext.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/PayloadTemplateContext.cs
----
using System.Globalization;
using System.Text;
using System.Text.Encodings.Web;
using System.Xml;
using Scriban;
using Scriban.Parsing;
using Scriban.Runtime;
namespace redb.Route.Templates;
///
/// A value the template author has marked as already safe for the result document
/// ({{ fragment | raw }}); written verbatim, bypassing media-type escaping.
///
public sealed class RawString
{
/// Wraps text that must not be escaped.
public RawString(string? value) => Value = value ?? string.Empty;
/// The text.
public string Value { get; }
///
public override string ToString() => Value;
}
///
/// How a value becomes text — shared by the Scriban and the Liquid context. Two steps, deliberately
/// apart: is the culture-invariant conversion (dates as ISO 8601) Scriban applies
/// wherever a value turns into a string inside the template (concatenation, filters), and
/// adds the escaping for the of the result, applied
/// exactly once, at the point a value is written to the output. Escaping inside ObjectToString
/// instead would escape a value again for every operator it passed through. Template literals never
/// come this way; is written verbatim.
///
internal static class PayloadValueFormatter
{
/// Value → text, culture-invariant, no escaping.
public static string ToText(object? value, Func fallback) => value switch
{
null => string.Empty,
RawString raw => raw.Value,
string s => s,
bool b => b ? "true" : "false",
DateTime dt => dt.ToString("o", CultureInfo.InvariantCulture),
DateTimeOffset dto => dto.ToString("o", CultureInfo.InvariantCulture),
IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
_ => fallback(),
};
/// Value → output text: , then escaped once for the media type; a verbatim.
public static string Format(object? value, MediaType mediaType, Func fallback)
=> value is RawString raw ? raw.Value : Escape(ToText(value, fallback), mediaType);
public static void Configure(TemplateContext context, RouteTemplateOptions options)
{
context.MemberRenamer = member => member.Name; // body.OrderId, not body.order_id
context.StrictVariables = options.StrictVariables;
context.EnableRelaxedMemberAccess = !options.StrictVariables;
context.LoopLimit = options.LoopLimit;
context.TemplateLoader = null; // no include from arbitrary paths (README decision 4)
}
private static string Escape(string text, MediaType mediaType) => mediaType switch
{
MediaType.Json => JavaScriptEncoder.UnsafeRelaxedJsonEscaping.Encode(text),
MediaType.Xml => XmlEscape(text),
_ => text,
};
///
/// The five XML entities, plus a replacement character for what XML 1.0 cannot carry at all:
/// control characters other than tab / LF / CR and lone surrogates. Left in, they would make the
/// document unparseable; U+FFFD is the same choice the JSON encoder makes for a lone surrogate.
///
private static string XmlEscape(string text)
{
var sb = new StringBuilder(text.Length + 16);
for (var i = 0; i < text.Length; i++)
{
var c = text[i];
switch (c)
{
case '&': sb.Append("&"); break;
case '<': sb.Append("<"); break;
case '>': sb.Append(">"); break;
case '"': sb.Append("""); break;
case '\'': sb.Append("'"); break;
default:
if (char.IsHighSurrogate(c) && i + 1 < text.Length && char.IsLowSurrogate(text[i + 1]))
sb.Append(c).Append(text[++i]);
else if (char.IsSurrogate(c) || !XmlConvert.IsXmlChar(c))
sb.Append('�');
else
sb.Append(c);
break;
}
}
return sb.ToString();
}
}
/// Scriban-syntax render context with media-type escaping (see ).
internal sealed class PayloadTemplateContext : TemplateContext
{
private readonly MediaType _mediaType;
public PayloadTemplateContext(MediaType mediaType, RouteTemplateOptions options)
{
_mediaType = mediaType;
PayloadValueFormatter.Configure(this, options);
}
/// Invariant text for every in-template conversion (concatenation, filters); no escaping here.
public override string ObjectToString(object? value, bool nested = false)
=> PayloadValueFormatter.ToText(value, () => base.ObjectToString(value, nested) ?? string.Empty);
/// The one place a value meets the result document: escaped here, once, whatever operators or filters produced it.
public override TemplateContext Write(SourceSpan span, object? textAsObject)
{
if (textAsObject is not null)
Write(PayloadValueFormatter.Format(textAsObject, _mediaType, () => ObjectToString(textAsObject)));
return this;
}
}
/// Liquid-syntax render context (Liquid filters such as upcase registered) with the same escaping.
internal sealed class LiquidPayloadTemplateContext : LiquidTemplateContext
{
private readonly MediaType _mediaType;
public LiquidPayloadTemplateContext(MediaType mediaType, RouteTemplateOptions options)
{
_mediaType = mediaType;
PayloadValueFormatter.Configure(this, options);
}
/// Invariant text for every in-template conversion (concatenation, filters); no escaping here.
public override string ObjectToString(object? value, bool nested = false)
=> PayloadValueFormatter.ToText(value, () => base.ObjectToString(value, nested) ?? string.Empty);
/// The one place a value meets the result document: escaped here, once, whatever operators or filters produced it.
public override TemplateContext Write(SourceSpan span, object? textAsObject)
{
if (textAsObject is not null)
Write(PayloadValueFormatter.Format(textAsObject, _mediaType, () => ObjectToString(textAsObject)));
return this;
}
}
Path: redb-route/redb.Route.Templates/PayloadTemplateDefinition.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/PayloadTemplateDefinition.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Definitions;
namespace redb.Route.Templates;
/// Where the rendered text goes.
public enum TemplateTarget
{
/// Message body (and ContentType from the media type).
Body,
/// A message header named by .
Header,
/// An exchange property named by .
Property,
}
///
/// The <payload> node: renders a template into the body, a header or a property.
/// Compiles the template at route build — a missing file or a syntax error fails Start()
/// with the template name and position. Declarative on purpose: the XML form and Message History
/// read , , and .
///
public sealed class PayloadTemplateDefinition : ProcessorDefinition
{
/// Creates the node.
public PayloadTemplateDefinition(TextSource source, MediaType mediaType, TemplateTarget target = TemplateTarget.Body, string? targetName = null, TemplateArgs? args = null)
{
Source = source ?? throw new ArgumentNullException(nameof(source));
MediaType = mediaType;
Target = target;
if (target != TemplateTarget.Body)
ArgumentException.ThrowIfNullOrWhiteSpace(targetName);
TargetName = targetName;
Args = args;
}
/// Template text origin.
public TextSource Source { get; }
/// Result type: drives escaping and ContentType.
public MediaType MediaType { get; }
/// Body, header or property.
public TemplateTarget Target { get; }
/// Header / property name when is not the body.
public string? TargetName { get; }
/// Named arguments evaluated before the render; null when none.
public TemplateArgs? Args { get; }
///
public override IProcessor CreateProcessor(IRouteContext context)
{
// Context services first (UseTemplates), then the DI container (AddRouteTemplates), then defaults.
var options = context.GetService()
?? context.GetServiceProvider()?.GetService(typeof(RouteTemplateOptions)) as RouteTemplateOptions
?? new RouteTemplateOptions();
// A relative path is looked up as every other file reference is: the context resolver (a
// package keeps its templates where only that resolver knows), then the base directory.
// A miss stays a template failure, not an IO one — the step promises one exception type.
TextSource source;
try
{
source = ResourceResolution.Locate(context, Source, options.BaseDirectory, "Template");
}
catch (FileNotFoundException ex)
{
throw new TemplateCompilationException(Source.Name, null, null, ex.Message, ex);
}
var compiled = TemplateEngine.Compile(source, options);
return new PayloadTemplateProcessor(compiled, MediaType, Target, TargetName, Args, options);
}
}
Path: redb-route/redb.Route.Templates/PayloadTemplateProcessor.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/PayloadTemplateProcessor.cs
----
using redb.Route.Abstractions;
namespace redb.Route.Templates;
/// Runtime side of : renders and writes the result to its target.
internal sealed class PayloadTemplateProcessor : IProcessor
{
private readonly CompiledTemplate _compiled;
private readonly MediaType _mediaType;
private readonly TemplateTarget _target;
private readonly string? _targetName;
private readonly TemplateArgs? _args;
private readonly RouteTemplateOptions _options;
public PayloadTemplateProcessor(CompiledTemplate compiled, MediaType mediaType, TemplateTarget target, string? targetName, TemplateArgs? args, RouteTemplateOptions options)
{
_compiled = compiled;
_mediaType = mediaType;
_target = target;
_targetName = targetName;
_args = args;
_options = options;
}
public Task Process(IExchange exchange, CancellationToken ct = default)
{
var text = TemplateEngine.Render(_compiled, exchange, _mediaType, _args, _options);
switch (_target)
{
case TemplateTarget.Header:
exchange.In.Headers[_targetName!] = text;
break;
case TemplateTarget.Property:
exchange.Properties[_targetName!] = text;
break;
default:
exchange.In.Body = text;
exchange.In.ContentType = ContentTypeOf(_mediaType);
break;
}
return Task.CompletedTask;
}
/// Content type written to the message when the target is the body.
public static string ContentTypeOf(MediaType mediaType) => mediaType switch
{
MediaType.Json => "application/json",
MediaType.Xml => "application/xml",
_ => "text/plain",
};
}
Path: redb-route/redb.Route.Templates/PayloadXmlContribution.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/PayloadXmlContribution.cs
----
using System.Xml.Linq;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Xml;
namespace redb.Route.Templates;
///
/// The <payload> element: a Scriban
/// template — referenced by a locator or inline in the content — rendered into the body (the
/// default), a header or an exchange property; <arg name=… expr=…/> /
/// <arg name=… value=…/> children feed the template model.
///
public sealed class PayloadXmlContribution : IXmlElementContribution
{
///
public string Name => "payload";
///
public XmlElementKind Kind => XmlElementKind.Step;
///
public ElementSpec Spec => new(Name, Kind,
[
new AttributeSpec("template", AttributeType.String) { Resource = true },
// The format spells the values lowercase (json/xml/text); parsing is case-insensitive.
new AttributeSpec("mediaType", AttributeType.Enum, Required: true, EnumValues: ["json", "xml", "text"]),
new AttributeSpec("target", AttributeType.String),
],
[ElementSpec.Child("arg", false,
new AttributeSpec("name", AttributeType.String, Required: true),
new AttributeSpec("value", AttributeType.String),
new AttributeSpec("expr", AttributeType.Expression))],
AllowsTextContent: true);
///
public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context)
{
var locator = context.Attr(element, "template");
var inline = Text(element);
if ((locator is null) == (inline is null))
{
context.AddError(element, " takes either the template locator or inline template content, not both.");
return current;
}
var mediaTypeName = context.RequiredAttr(element, "mediaType");
if (mediaTypeName is null)
return current;
if (!Enum.TryParse(mediaTypeName, ignoreCase: true, out var mediaType))
{
context.AddError(element, $"'{mediaTypeName}' is not a media type ({string.Join(", ", Enum.GetNames())}).");
return current;
}
var arguments = new List<(string Name, string? Expr, string? Value)>();
foreach (var child in element.Elements().Where(c => c.Name.LocalName == "arg"))
{
var name = context.RequiredAttr(child, "name");
var pick = context.ExactlyOneOf(child, "value", "expr");
if (name is null || pick is null)
continue;
arguments.Add((name,
pick.Value.Name == "expr" ? pick.Value.Value : null,
pick.Value.Name == "value" ? pick.Value.Value : null));
}
Action? args = arguments.Count == 0 ? null : model =>
{
foreach (var (name, expr, value) in arguments)
{
if (expr is not null) model.Set(name, expr);
else model.SetValue(name, value);
}
};
var source = locator is null ? TextSource.Inline(inline!) : TextSource.FromLocator(locator);
var target = context.Attr(element, "target") ?? "body";
if (target == "body")
return current.SetBodyTemplate(source, mediaType, args);
if (target.StartsWith("header:", StringComparison.Ordinal))
return current.SetHeaderTemplate(target["header:".Length..], source, mediaType, args);
if (target.StartsWith("property:", StringComparison.Ordinal))
return current.SetPropertyTemplate(target["property:".Length..], source, mediaType, args);
context.AddError(element, $"target='{target}' is not valid — body (default), header:Name or property:Name.");
return current;
}
///
public void Print(XElement element, XmlCodeWriter code)
{
var source = element.Attribute("template")?.Value is { } locator
? $"TextSource.FromLocator({XmlCodeWriter.Str(locator)})"
: $"TextSource.Inline({XmlCodeWriter.Str(Text(element) ?? "")})";
var mediaType = $"MediaType.{Enum.Parse(element.Attribute("mediaType")?.Value ?? "Json", true)}";
var argCalls = element.Elements().Where(c => c.Name.LocalName == "arg")
.Select(c => c.Attribute("expr")?.Value is { } expr
? $".Set({XmlCodeWriter.Str(c.Attribute("name")?.Value ?? "")}, {XmlCodeWriter.Str(expr)})"
: $".SetValue({XmlCodeWriter.Str(c.Attribute("name")?.Value ?? "")}, {XmlCodeWriter.Str(c.Attribute("value")?.Value ?? "")})")
.ToList();
var args = argCalls.Count == 0 ? null : "a => a" + string.Concat(argCalls);
var target = element.Attribute("target")?.Value ?? "body";
if (target == "body")
code.Verb(element, "SetBodyTemplate", args is null ? [source, mediaType] : [source, mediaType, args]);
else if (target.StartsWith("header:", StringComparison.Ordinal))
code.Verb(element, "SetHeaderTemplate", args is null
? [XmlCodeWriter.Str(target["header:".Length..]), source, mediaType]
: [XmlCodeWriter.Str(target["header:".Length..]), source, mediaType, args]);
else
code.Verb(element, "SetPropertyTemplate", args is null
? [XmlCodeWriter.Str(target["property:".Length..]), source, mediaType]
: [XmlCodeWriter.Str(target["property:".Length..]), source, mediaType, args]);
}
private static string? Text(XElement element)
{
var text = string.Concat(element.Nodes().OfType().Select(t => t.Value));
return string.IsNullOrWhiteSpace(text) ? null : text.Trim();
}
}
Path: redb-route/redb.Route.Templates/README.md
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/README.md
----
# redb.Route.Templates
> Documentation and articles:
Build a payload from a template instead of concatenating strings: the analog of WSO2 PayloadFactory
and Camel's templating components, on [Scriban](https://github.com/scriban/scriban). Templates
live in files, embedded resources or inline; the result type is explicit so substituted values are
escaped correctly for JSON or XML.
```csharp
.SetBodyTemplate("Templates/order-confirm.json.sbn", MediaType.Json, a => a
.Set("customer", "header.customerId") // route expression language
.Set("total", "header.amount * header.qty")
.SetValue("channel", "email")) // constant
```
```scriban
{
"id": {{ headers.orderId }},
"customer": "{{ args.customer }}",
"items": [
{{~ for i in body.items ~}}
{ "sku": "{{ i.sku }}", "qty": {{ i.qty }} }{{ if !for.last }},{{ end }}
{{~ end ~}}
]
}
```
## Rules
| Rule | Why |
|---|---|
| A `string` argument is a **locator**: a file path or `assembly:Name/Path/file.sbn`. Inline text is `TextSource.Inline("...")`. | A string never has to be guessed as "path or text" — the same rule the route expression language follows. |
| A relative path is looked up by the context's `IRouteResourceResolver` first, then by `RouteTemplateOptions.BaseDirectory` (default `AppContext.BaseDirectory`). A miss names both places. | One lookup order for the whole framework: the same one `validateXsd`, `xslt` and the XML context files use. A route inside a `.tpkg` keeps its template in `resources/`, which only the package resolver knows about — the base directory stays the worker's. |
| `MediaType` is mandatory: `Json`, `Xml`, `Text`. | It decides escaping of substituted values (`"`/`\`/control characters for JSON; `& < > " '` for XML) and the `ContentType` of the produced body. Template literals are never escaped — only values. `{{ x \| raw }}` writes a value verbatim. |
| Numbers and dates render culture-invariant; dates as ISO 8601. | A payload must not depend on the server locale. |
| Compiled at route build, cached by source. | A missing file or a syntax error fails `Start()` with the template name and `(line,column)`. |
| Sandbox: no `include`, no context objects, .NET objects expose public properties and fields only. | Templates are data, not code. A method call on a body object fails the render, and so does one inside `expr(...)` or an argument expression: those run under `ExpressionSandbox`, where the expression engine refuses reflection calls (its built-in helpers such as `contains`, `substring`, `length` keep working). |
## Data model in a template
| Name | What |
|---|---|
| `body` | JSON text → object tree (`body.order.id`); XML text → navigable tree (`body.order.item[0].sku`, attributes and child elements as members, repeated children as arrays, element text under `text`); POCO → its public members with their C# names; dictionaries → members |
| `headers.name`, `headers["Content-Type"]` | message headers |
| `properties.name` | exchange properties |
| `exception.message`, `.type`, `.stackTrace` | current exception or `null` |
| `args.name` | named arguments of the step |
| `expr("header.amount * header.qty")` | any route-language expression, evaluated by the same engine as `${...}` |
| `raw(value)` / `{{ value \| raw }}` | skip escaping for this value |
## Options
```csharp
services.AddRouteTemplates(o => { o.BaseDirectory = "/etc/acme/templates"; o.Liquid = false; });
// or, without DI:
context.UseTemplates(o => o.StrictVariables = true);
```
`Liquid = true` switches to Scriban's Liquid-compatible syntax. `StrictVariables` makes a missing
variable a render error instead of an empty string. `LoopLimit` (default 10 000) bounds loops.
## Targets
`SetBodyTemplate` (body + `ContentType`), `SetHeaderTemplate(name, ...)`, `SetPropertyTemplate(key, ...)`.
## XML form
The same node in an XML route ([redb.Route.Xml](../redb.Route.Xml/README.md)):
```xml
]]>
```
Path: redb-route/redb.Route.Templates/RouteTemplateOptions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/RouteTemplateOptions.cs
----
namespace redb.Route.Templates;
///
/// Package-wide settings, registered with services.AddRouteTemplates(...) or
/// context.UseTemplates(...); defaults apply when neither was called.
///
public sealed class RouteTemplateOptions
{
/// Directory relative template paths are resolved against. Default: .
public string BaseDirectory { get; set; } = AppContext.BaseDirectory;
/// Parse templates with Scriban's Liquid-compatible syntax instead of the native {{ }} syntax. Default: false.
public bool Liquid { get; set; }
/// Fail a render when the template reads a variable that does not exist (Scriban StrictVariables). Default: false — a missing value renders empty.
public bool StrictVariables { get; set; }
/// Upper bound on loop iterations per render, a guard against a runaway template. Default: 10 000.
public int LoopLimit { get; set; } = 10_000;
}
Path: redb-route/redb.Route.Templates/TemplateArgs.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Templates/TemplateArgs.cs
----
using redb.Route.Abstractions;
using redb.Route.Expressions;
namespace redb.Route.Templates;
///
/// Named arguments of a payload step — the analog of WSO2 PayloadFactory <arg>, but by
/// name instead of position: args.Set("customer", "header.customerId") is read in the template
/// as {{ args.customer }}. Argument expressions are the route expression language and are
/// evaluated on the message before rendering, which keeps the template itself an almost
/// static document a non-programmer can edit.
///
public sealed class TemplateArgs
{
private readonly Dictionary _expressions = new(StringComparer.Ordinal);
private readonly Dictionary _constants = new(StringComparer.Ordinal);
/// Argument computed from a route-language expression ("header.amount * header.qty"); the expression is compiled now, so a typo fails at Start().
public TemplateArgs Set(string name, string expression)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
ArgumentException.ThrowIfNullOrWhiteSpace(expression);
return Set(name, new StringExpression(expression));
}
/// Argument computed from an .
public TemplateArgs Set(string name, IExpression expression)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
ArgumentNullException.ThrowIfNull(expression);
_constants.Remove(name);
_expressions[name] = expression;
return this;
}
/// Constant argument (XML form <arg name="channel" value="email"/>).
public TemplateArgs SetValue(string name, object? value)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
_expressions.Remove(name);
_constants[name] = value;
return this;
}
/// Argument names, for diagnostics.
public IEnumerable Names => _expressions.Keys.Concat(_constants.Keys);
/// Evaluates every argument against the exchange.
internal Dictionary Evaluate(IExchange exchange)
{
var result = new Dictionary(_constants, StringComparer.Ordinal);
foreach (var (name, expression) in _expressions)
result[name] = expression.Evaluate