Text and HTML templates
suggest changeA template is text with holes in it: an email body, an HTML page, a config file, generated source code. At run time you fill the holes with data.
C# gives you several ways to do it, from built-in language features to full template engines:
- Interpolated raw string literals (
$"""...""") for templates that live in your code. - Interpolated string handlers to make the compiler encode HTML for you.
Regex.ReplaceorCompositeFormatfor simple templates loaded at run time.- Scriban and Fluid (Liquid) for templates written by non-programmers or stored outside the program.
- Razor components rendered with
HtmlRendererfor type-checked HTML templates outside ASP.NET Core.
For HTML there's one rule that matters more than the choice of tool: every value that comes from data must be HTML-encoded, or you have a cross-site scripting (XSS) bug.
Examples use C# 14 / .NET 10 and run as file-based programs (dotnet run app.cs), except the Razor one, which needs a project.
Interpolated raw strings as templates
For templates that are part of your program, you don't need a library. Raw string literals (C# 11) are multi-line, don't need escaping of quotes, and strip the indentation of the closing """ from every line:
var order = new Order(1042, "Alice", 129.5m);
string text = $"""
Dear {order.Customer},
Thank you for order #{order.Id}.
Total: {order.Total,10:N2} USD
""";
Console.WriteLine(text);
string json = $$"""
{ "id": {{order.Id}}, "customer": "{{order.Customer}}" }
""";
Console.WriteLine(json);
record Order(int Id, string Customer, decimal Total);
Dear Alice,
Thank you for order #1042.
Total: 129.50 USD
{ "id": 1042, "customer": "Alice" }
Holes use the usual string interpolation syntax, including alignment (,10) and format strings (:N2), described in String Format.
When the output itself contains braces (JSON, CSS, JavaScript), start the literal with two dollar signs. Then {{...}} is a hole and a single { is literal text.
The compiler checks every hole, so a typo in a property name is a build error, not a blank in the output. The downside: the template is compiled into the program and can't be edited without rebuilding.
Encoding values in HTML
String interpolation doesn't know it's producing HTML:
using System.Net;
using System.Text.Encodings.Web;
string name = "<script>alert('hi')</script> & Co";
// WRONG: user input goes into HTML as-is
Console.WriteLine($"<p>Hello, {name}</p>");
// right: encode every value that goes into HTML
Console.WriteLine($"<p>Hello, {WebUtility.HtmlEncode(name)}</p>");
Console.WriteLine($"<p>Hello, {HtmlEncoder.Default.Encode(name)}</p>");
// attributes need encoding too, and must be quoted
string url = "/search?q=a\" onmouseover=\"alert(1)";
Console.WriteLine($"<a href=\"{WebUtility.HtmlEncode(url)}\">search</a>");
// in URLs, encode query values with Uri.EscapeDataString
Console.WriteLine($"<a href=\"/search?q={Uri.EscapeDataString("C# & .NET")}\">search</a>");
<p>Hello, <script>alert('hi')</script> & Co</p>
<p>Hello, <script>alert('hi')</script> & Co</p>
<p>Hello, <script>alert('hi')</script> & Co</p>
<a href="/search?q=a" onmouseover="alert(1)">search</a>
<a href="/search?q=C%23%20%26%20.NET">search</a>
Both encoders are in the base library:
WebUtility.HtmlEncode(System.Net) encodes<,>,&,"and'.HtmlEncoder.Default(System.Text.Encodings.Web) is what ASP.NET Core uses. It's stricter: it also encodes non-ASCII characters (ébecomesé) unless you create one withHtmlEncoder.Create(UnicodeRanges.All).
Encoding is context-specific. HTML encoding is correct for element text and quoted attribute values. Values inside a URL need Uri.EscapeDataString, and values inside <script> need JavaScriptEncoder or, better, JSON serialization. Never put data into an unquoted attribute.
Templates as functions
A template that takes parameters is just a function returning a string. Small functions compose into pages, loops become string.Join over Select, and conditionals become ?: or an if:
using static System.Net.WebUtility;
var products = new List<Product>
{
new("Keyboard", 49.99m, InStock: true),
new("Mouse <wireless>", 19.5m, InStock: false),
new("Monitor", 189m, InStock: true),
};
Console.WriteLine(Page("Products", ProductTable(products)));
static string Page(string title, string body) => $"""
<!doctype html>
<html>
<head><title>{HtmlEncode(title)}</title></head>
<body>
<h1>{HtmlEncode(title)}</h1>
{body}
</body>
</html>
""";
static string ProductTable(IEnumerable<Product> items)
{
if (!items.Any())
return "<p>No products.</p>";
string rows = string.Join("\n", items.Select(p => $"""
<tr class="{(p.InStock ? "in" : "out")}">
<td>{HtmlEncode(p.Name)}</td>
<td>{p.Price:0.00}</td>
</tr>
"""));
return $"""
<table>
{rows}
</table>
""";
}
record Product(string Name, decimal Price, bool InStock);
<!doctype html>
<html>
<head><title>Products</title></head>
<body>
<h1>Products</h1>
<table>
<tr class="in">
<td>Keyboard</td>
<td>49.99</td>
</tr>
<tr class="out">
<td>Mouse <wireless></td>
<td>19.50</td>
</tr>
<tr class="in">
<td>Monitor</td>
<td>189.00</td>
</tr>
</table>
</body>
</html>
{body} is not encoded because it's HTML built by another template. That's the weak spot of this approach: everything is a string, so nothing tells you whether a string is plain text that needs encoding or HTML that must not be encoded again. Forget one HtmlEncode and you have an XSS hole.
Numbers and dates are formatted with the current culture. For output that must not depend on the machine's locale, format with CultureInfo.InvariantCulture or use string.Create(CultureInfo.InvariantCulture, $"...").
Automatic encoding with an interpolated string handler
Since C# 10 you can write your own interpolated string handler: a type the compiler calls for each literal part and each hole of $"...". That lets you build HTML where the literal parts are trusted and every hole is encoded, unless it's already HTML:
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
string user = "Bob <admin>";
int unread = 3;
Html greeting = Html.Format($"<p>Hello, <b>{user}</b>! You have {unread} new messages.</p>");
Console.WriteLine(greeting);
// already-safe HTML is inserted as-is, so fragments compose without double encoding
Html page = Html.Format($"<div class=\"box\">{greeting}</div>");
Console.WriteLine(page);
// a sequence of fragments
string[] tags = ["c#", "<html>", "templates"];
Html list = Html.Format($"<ul>{tags.Select(t => Html.Format($"<li>{t}</li>"))}</ul>");
Console.WriteLine(list);
// a string of HTML that you trust must be marked explicitly
Html raw = Html.Format($"<div>{Html.Raw("<hr>")}</div>");
Console.WriteLine(raw);
// HTML that is already safe; ToString() returns it unchanged
public readonly record struct Html(string Value)
{
public static Html Raw(string html) => new(html);
public static Html Format(HtmlHandler handler) => new(handler.ToStringAndClear());
public override string ToString() => Value;
}
[InterpolatedStringHandler]
public ref struct HtmlHandler
{
private readonly StringBuilder _sb;
public HtmlHandler(int literalLength, int formattedCount) =>
_sb = new StringBuilder(literalLength + formattedCount * 16);
// literal parts of the template are trusted
public void AppendLiteral(string s) => _sb.Append(s);
public void AppendFormatted(Html html) => _sb.Append(html.Value);
public void AppendFormatted(IEnumerable<Html> items)
{
foreach (var h in items) _sb.Append(h.Value);
}
// everything else is encoded
public void AppendFormatted<T>(T value, string? format = null)
{
string? s = value is IFormattable f ? f.ToString(format, null) : value?.ToString();
_sb.Append(WebUtility.HtmlEncode(s));
}
public string ToStringAndClear()
{
string s = _sb.ToString();
_sb.Clear();
return s;
}
}
<p>Hello, <b>Bob <admin></b>! You have 3 new messages.</p>
<div class="box"><p>Hello, <b>Bob <admin></b>! You have 3 new messages.</p></div>
<ul><li>c#</li><li><html></li><li>templates</li></ul>
<div><hr></div>
When Html.Format takes an HtmlHandler parameter, the compiler rewrites Html.Format($"<p>{user}</p>") into calls to AppendLiteral("<p>"), AppendFormatted(user) and AppendLiteral("</p>"). Overload resolution picks AppendFormatted(Html) for safe fragments and the generic overload, which encodes, for everything else.
The type system now tracks what's safe: a string is always encoded, an Html never is, and turning an arbitrary string into Html needs a visible Html.Raw call that's easy to find in a code review. This is the same idea as HtmlString in ASP.NET Core and MarkupString in Razor components.
Simple runtime templates with Regex
When the template text comes from a file, a database or an admin screen, the compiler can't help. For simple "replace {{name}} with a value" templates, a regular expression is enough:
using System.Text.RegularExpressions;
// template text could come from a file, a database or a config setting
string template = "Hi {{ name }}, your order {{orderId}} ships on {{date}}. {{unknown}}";
var values = new Dictionary<string, object>
{
["name"] = "Alice",
["orderId"] = 1042,
["date"] = new DateOnly(2026, 10, 20),
};
Console.WriteLine(Render(template, values));
static string Render(string template, IReadOnlyDictionary<string, object> values) =>
Placeholder().Replace(template, m =>
{
string key = m.Groups[1].Value;
return values.TryGetValue(key, out var v) ? Convert.ToString(v) ?? "" : m.Value;
});
partial class Program
{
[GeneratedRegex(@"\{\{\s*(\w+)\s*\}\}")]
private static partial Regex Placeholder();
}
Hi Alice, your order 1042 ships on 10/20/2026. {{unknown}}
[GeneratedRegex] makes the source generator build the regex at compile time (see Regex). Unknown placeholders are left in place so they're easy to spot. Depending on your needs you might throw instead, or replace them with an empty string.
This works for names only. As soon as you need loops, conditionals or formatting inside the template, don't extend it: use a template engine.
CompositeFormat for numbered placeholders
Localized messages are often stored as string.Format templates in resource files: "{0} has {1:N0} points". If you format the same template many times, parse it once with CompositeFormat (.NET 8+):
using System.Globalization;
using System.Text;
// e.g. loaded from a resource file for the current language
string formatText = "{0} has {1:N0} points ({2:P1} of total)";
// parse once, reuse many times
CompositeFormat fmt = CompositeFormat.Parse(formatText);
Console.WriteLine($"placeholders needed: {fmt.MinimumArgumentCount}");
var inv = CultureInfo.InvariantCulture;
Console.WriteLine(string.Format(inv, fmt, "Alice", 12500, 0.4167));
Console.WriteLine(string.Format(CultureInfo.GetCultureInfo("de-DE"), fmt, "Bob", 9800, 0.3267));
try
{
CompositeFormat.Parse("{0} has {1 points");
}
catch (FormatException e)
{
Console.WriteLine($"bad template: {e.Message}");
}
placeholders needed: 3
Alice has 12,500 points (41.7 % of total)
Bob has 9.800 points (32,7 % of total)
bad template: Input string was not in a correct format. Failure to parse near offset 11. Format item ends prematurely.
Parse validates the template up front, so a broken translation fails when it's loaded rather than when the message is first shown. MinimumArgumentCount lets you check that a translation doesn't refer to arguments you don't pass.
Scriban
Scriban is a fast, popular template engine with its own small scripting language: variables, loops, conditionals, functions and pipes. It also understands Liquid syntax.
#:package Scriban@7.5.1
#:property PublishAot=false
using Scriban;
var template = Template.Parse("""
Hello {{ name }}!
{{ for item in items -}}
- {{ item.name | string.upcase }}: {{ item.price | math.format "0.00" }}
{{ end -}}
{{ items.size }} items, {{ if paid }}paid{{ else }}not paid{{ end }}
""");
string result = template.Render(new
{
Name = "Alice",
Paid = false,
Items = new[]
{
new { Name = "Keyboard", Price = 49.99m },
new { Name = "Mouse", Price = 19.5m },
},
});
Console.WriteLine(result);
Hello Alice!
- KEYBOARD: 49.99
- MOUSE: 19.50
2 items, not paid
Things to know:
Template.Parsecompiles the template. Parse once and callRendermany times; a parsedTemplateis safe to share.- By default .NET member names are renamed to snake_case:
Namebecomesname,OrderIdbecomesorder_id. |pipes a value into a function. Scriban ships with a large library:string.*,array.*,math.*,date.*,html.*and more.- A
-inside the braces ({{-or-}}) removes whitespace including newlines on that side, which is how you keep loops from producing blank lines.~removes spaces but keeps the newline. Render(object)uses reflection, hencePublishAot=false(file-based programs default to Native AOT). For AOT builds useRender(TemplateContext)with aScriptObject.
HTML, errors and custom functions
#:package Scriban@7.5.1
#:property PublishAot=false
using Scriban;
using Scriban.Runtime;
// 1. syntax errors are reported, not thrown
var bad = Template.Parse("{{ for x in items }}{{ x }}");
if (bad.HasErrors)
{
foreach (var msg in bad.Messages)
Console.WriteLine(msg);
}
// 2. HTML: Scriban does NOT escape automatically, use html.escape
var page = Template.Parse("""
<ul>
{{- for c in comments }}
<li><b>{{ c.author | html.escape }}</b>: {{ c.text | html.escape }}</li>
{{- end }}
</ul>
""");
// 3. a ScriptObject gives full control over what the template can see
var model = new ScriptObject();
model.Add("comments", new[]
{
new Comment("Ann", "Nice post!"),
new Comment("Eve", "<img src=x onerror=alert(1)>"),
});
// expose a C# function to the template
model.Import("shout", new Func<string, string>(s => s.ToUpperInvariant() + "!"));
var context = new TemplateContext();
context.PushGlobal(model);
Console.WriteLine(page.Render(context));
Console.WriteLine(Template.Parse("{{ shout 'hello' }}").Render(context));
record Comment(string Author, string Text);
<input>(1,26) : error : Error while parsing for statement: The <end> statement was not found in: for <variable> in <expression> ... end
<ul>
<li><b>Ann</b>: Nice post!</li>
<li><b>Eve</b>: <img src=x onerror=alert(1)></li>
</ul>
HELLO!
Always check HasErrors after parsing a template you didn't write; rendering a template with errors throws. Pass a file name as the second argument of Template.Parse and messages will show it instead of <input>.
The big caveat for HTML is in the output: Scriban doesn't escape anything unless you write | html.escape. That's fine for emails and code generation, risky for web pages. If you need HTML, consider Fluid or Razor, which encode by default.
Fluid (Liquid templates)
Fluid implements Liquid, the template language from Shopify and Jekyll. Liquid is a good choice when users of your application write templates, because many already know it and it's sandboxed: templates can only read the members you allow.
#:package Fluid.Core@2.40.0
#:property PublishAot=false
using System.Text.Encodings.Web;
using Fluid;
var parser = new FluidParser();
string source = """
<h1>{{ title }}</h1>
<ul>
{%- for c in comments %}
<li>{{ c.author }} ({{ c.text | size }} chars): {{ c.text | truncate: 20 }}</li>
{%- endfor %}
</ul>
""";
if (!parser.TryParse(source, out IFluidTemplate template, out string error))
{
Console.WriteLine(error);
return;
}
var options = new TemplateOptions();
options.MemberAccessStrategy.MemberNameStrategy = MemberNameStrategies.CamelCase;
options.MemberAccessStrategy.Register<Comment>(); // allow-list types the template may read
var model = new
{
Title = "Comments & replies",
Comments = new[]
{
new Comment("Ann", "Nice post!"),
new Comment("Eve", "<script>alert(1)</script>"),
},
};
var context = new TemplateContext(model, options);
// passing an HtmlEncoder makes every {{ }} output HTML-encoded
string html = await template.RenderAsync(context, HtmlEncoder.Default);
Console.WriteLine(html);
record Comment(string Author, string Text);
<h1>Comments & replies</h1>
<ul>
<li>Ann (10 chars): Nice post!</li>
<li>Eve (25 chars): <script>alert(1)<...</li>
</ul>
Notes:
{{ }}outputs a value,{% %}is a tag (for,if,assign, ...), and|applies a filter.- The members of the model object are visible, but other types must be registered with
MemberAccessStrategy.Register<T>(). Without that line both<li>elements render as( chars):with no error. Unknown members silently render as empty, which is a Liquid design decision you'll want to remember when debugging. MemberNameStrategies.CamelCaselets templates writec.authorfor theAuthorproperty. The default uses .NET names as-is.- Encoding happens on output with the encoder you pass to
RenderAsync, so filters liketruncatework on the raw text and the result is encoded afterwards. Use therawfilter for a value that is already HTML. - Parse once and cache the
IFluidTemplate; it's thread-safe. Create a newTemplateContextper render.
Razor components without ASP.NET
Razor is the HTML template language of ASP.NET Core. Since .NET 8 you can render Razor components to a string in any app, such as a console program generating emails or static HTML pages, with HtmlRenderer. You get C# in the template, compile-time checking and automatic HTML encoding.
Razor files need the Razor SDK, so this one is a regular project:
<!-- RazorTemplates.csproj -->
<Project Sdk="Microsoft.NET.Sdk.Razor">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="10.0.13" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="10.0.13" />
</ItemGroup>
</Project>
The template is a component. Parameters are properties marked with [Parameter]:
@* OrderEmail.razor *@
<h1>Hi @Customer,</h1>
<p>Thanks for order #@OrderId.</p>
@if (Items.Count == 0)
{
<p>Your cart is empty.</p>
}
else
{
<table>
@foreach (var item in Items)
{
<tr class="@(item.Price > 100 ? "big" : null)">
<td>@item.Name</td>
<td>@item.Price.ToString("0.00")</td>
</tr>
}
</table>
}
<p>Total: <b>@Items.Sum(i => i.Price).ToString("0.00")</b></p>
@code {
[Parameter] public string Customer { get; set; } = "";
[Parameter] public int OrderId { get; set; }
[Parameter] public List<LineItem> Items { get; set; } = [];
}
Rendering must happen on the renderer's dispatcher:
// Program.cs
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RazorTemplates; // namespace of OrderEmail.razor (the project name)
var services = new ServiceCollection();
services.AddLogging();
await using var provider = services.BuildServiceProvider();
var loggerFactory = provider.GetRequiredService<ILoggerFactory>();
await using var renderer = new HtmlRenderer(provider, loggerFactory);
string html = await renderer.Dispatcher.InvokeAsync(async () =>
{
var parameters = ParameterView.FromDictionary(new Dictionary<string, object?>
{
[nameof(OrderEmail.Customer)] = "Alice <alice@example.com>",
[nameof(OrderEmail.OrderId)] = 1042,
[nameof(OrderEmail.Items)] = new List<LineItem>
{
new("Keyboard", 49.99m),
new("Monitor", 189m),
},
});
var output = await renderer.RenderComponentAsync<OrderEmail>(parameters);
return output.ToHtmlString();
});
Console.WriteLine(html);
public record LineItem(string Name, decimal Price);
<h1>Hi Alice <alice@example.com>,</h1>
<p>Thanks for order #1042.</p><table><tr><td>Keyboard</td>
<td>49.99</td></tr><tr class="big"><td>Monitor</td>
<td>189.00</td></tr></table><p>Total: <b>238.99</b></p>
What you get for the extra setup:
@expressionis always HTML-encoded. To output trusted HTML, pass aMarkupString:@((MarkupString)html).- An attribute whose value is
nullorfalseis omitted entirely, as the first<tr>shows. - Components nest like functions:
<Header Title="..." />inside another component, withRenderFragmentparameters for layouts. - The compiler checks everything; renaming a property breaks the build instead of the output.
- The Razor compiler drops insignificant whitespace between elements, so the HTML is compact but not pretty.
The trade-off is that templates are compiled into the program, like interpolated strings. Razor is a good fit for HTML emails and static site generation, not for templates that users edit.
Choosing an approach
| Need | Use |
|---|---|
| Short text built in code | Interpolated (raw) strings |
| HTML built in code, small amount | Interpolated strings with an encoding handler, or careful HtmlEncode |
| HTML built in code, many pages | Razor components with HtmlRenderer |
| Replace a few named fields in a stored template | Regex.Replace with a dictionary |
| Localized messages | CompositeFormat with resource strings |
| Stored templates with loops and conditions | Scriban or Fluid |
| Templates written by users | Fluid (sandboxed, HTML-encodes by default) |
Tips
- Encode at output, in the template. Don't store HTML-encoded strings in your database; store the raw text and encode it where it's written into HTML.
- Prefer engines that encode by default (Razor, Fluid with an
HtmlEncoder) for HTML. Opt-in escaping, as in Scriban or plain interpolation, is easy to forget. - Parse templates once. Parsing is the slow part. Cache parsed Scriban/Fluid templates and
CompositeFormatobjects, for example in a static field or aConcurrentDictionarykeyed by template name. - Validate stored templates when they're saved or loaded, not when the first customer email is sent: check
HasErrors,TryParse, or catchFormatExceptionfromCompositeFormat.Parse. - Don't build JSON, XML or SQL with templates. Use
JsonSerializer,XDocumentand parameterized queries; they handle escaping correctly. - Be careful with culture. Numbers and dates in templates use the current culture unless you pass
CultureInfo.InvariantCultureor the user's culture explicitly. - For generating C# code at build time, use source generators (or T4 templates in older projects) instead of runtime templates.