---
title: "LLM prompt templates with variables in C#"
url: https://recursiveai.org/onellm/cookbook/render-prompt-template/
description: "Render prompt variables and conditionals in C# with OneLLM, reject missing keys, and send the rendered text to a scripted model without an API key."
version: "1.0.1"
---

# LLM prompt templates with variables in C#

**OneLLM** is a free, open-source LLM and agent library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneLlm) · [GitHub](https://github.com/recursive-ai-oss/onellm-csharp) · [Docs](https://recursiveai.org/onellm/docs/) · [Download example (.zip)](https://recursiveai.org/onellm/cookbook/render-prompt-template/render-prompt-template.zip)

Render reusable instructions with variables and conditionals before sending them to a model.

```shell
dotnet add package RecursiveAI.OneLlm
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using OneLlm.Templating;

Dictionary<string, object?> values = new()
    { ["name"] = "Ada", ["brief"] = true };
Console.WriteLine(Template.Render(
    "Hi {{ .name }}." +
    "{{ if .brief }} Be brief.{{ end }}",
    values));
```

Unzip [the example](https://recursiveai.org/onellm/cookbook/render-prompt-template/render-prompt-template.zip), then `dotnet run`.

The zip holds the full program below. To run only the snippet at the top, paste it into `Program.cs` of a new console app and install the package above. That snippet prints:

```text
Hi Ada. Be brief.
```

## The full program

The download renders a name and a conditional, checks a missing key, then sends the rendered string to a scripted model. Both the template and its values are shown below; no input files or API keys are needed. The model’s answer is scripted, not a live completion. Here, `gpt-6-luna` is a placeholder model name that works with the scripted provider; it does not select a live model.

With `MissingKeyMode.Error`, a missing map key throws `TemplateException` with its kind and source position.

```csharp
using OneLlm;
using OneLlm.Templating;
using OneLlm.Testing;

var scope = new Dictionary<string, object?>
{
    ["name"] = "Ada",
    ["brief"] = true
};
string prompt = Template.Render(
    "Explain C# to {{ .name }}.{{ if .brief }} Be brief.{{ end }}", scope);
Console.WriteLine(prompt);

try
{
    Template.Render("Hello {{ .missing }}", scope,
        render: new() { MissingKey = MissingKeyMode.Error });
}
catch (TemplateException error)
{
    Console.WriteLine($"Missing key: {error.Detail} ({error.Kind} at {error.Line}:{error.Column})");
}

var provider = new ScriptedProvider("openai");
provider.Enqueue(ScriptStep.Text("C# is a programming language."));
Llm.Default = new Runtime();
Llm.Default.Providers.Set("openai", provider);
Console.WriteLine(await Llm.AskAsync("gpt-6-luna", prompt));
Console.WriteLine("Sent prompt: " + provider.Requests[0].Messages[^1].GetUserText());
```

Running `dotnet run` from the unzipped example prints:

```text
Explain C# to Ada. Be brief.
Missing key: map has no entry for key "missing" (Execute at 1:10)
C# is a programming language.
Sent prompt: Explain C# to Ada. Be brief.
```

## Variations

Parse a reusable template and transform a value with the `upper` function:

```csharp
using OneLlm.Templating;

var prompt = Template.Parse("Hello {{ .name | upper }}");
Console.WriteLine(prompt.Render(
    new Dictionary<string, object?> { ["name"] = "Ada" }));
```


```text
Hello ADA
```

## Related recipes

- [Test LLM code without an API key](https://recursiveai.org/onellm/cookbook/test-llm-code-without-api-key/)
- [Stream a chat response](https://recursiveai.org/onellm/cookbook/stream-chat-response/)

## The short answer

Use `OneLlm.Templating.Template.Render` with a string and a map of values. A dot selects a key from the current scope; `if` includes text conditionally. The result is ordinary text, so it can be inspected or tested before a model sees it. Rendering itself requires no provider and makes no model call.

## How do I pass variables to an LLM prompt template in C#?

Supply a `Dictionary<string, object?>` as the scope. The snippet at the top uses two keys: `name` is a string, and `brief` is a Boolean. The template inserts the name and includes the extra instruction only when the Boolean is true. The full program then passes that rendered prompt to `Llm.AskAsync`.

The engine reads plain values directly, without reflection. The [templating reference](https://recursiveai.org/onellm/docs/templating/) lists string-keyed maps, lists, arrays, booleans, numbers, strings, null and `JsonElement` as scope values. Keep the scope explicit rather than expecting the engine to discover arbitrary properties on your application objects.

The template language follows Go’s `text/template` syntax, including pipelines, variables, conditionals and ranges. The variation pipes a name through `upper`. For nested data, use nested maps and field chains. The engine itself only needs the map you pass; names such as `inputs` have meaning because a host supplies them, not because the renderer automatically fills them.

## How do I handle missing prompt-template variables?

Choose between permissive and strict rendering. The default, `MissingKeyMode.Default`, prints `<no value>` for a missing map key. `MissingKeyMode.Error` instead fails and names the key. A null value also prints `<no value>` under the documented value rules, so avoid using rendered placeholder text as your only input validation.

The full program explicitly selects error mode for a missing key and catches `TemplateException`. Its output names the missing key through `TemplateException.Detail` and identifies an execution error and a source location. The exception also carries the template name, byte offset and detail. Parse errors and execution errors are distinct kinds, which helps separate invalid template syntax from a valid template rendered against incomplete data.

Use strict mode when missing information would produce an unusable prompt. Use default mode only when its placeholder behavior is acceptable to your caller. Catching the exception does not supply the missing information: fix the values or deliberately choose a fallback before making a real model request.

## Can I reuse prompt templates with conditionals and functions?

Yes. Parse with `Template.Parse` and render the returned template against each scope, as the variation does. Parsed templates are cached and immutable; the documentation describes rendering as thread-safe. Each render still receives its own data, so a reusable prompt need not hard-code a person’s name or a particular set of instructions.

Code examples inside prompts need special care. By default the engine escapes template delimiters inside Markdown fenced blocks and inline code spans so they print literally. A template expression placed inside such a region will not substitute as ordinary prompt text does. `TemplateParseOptions.EscapeCodeRegions` can turn that behavior off when substitution inside code is intentional.

The renderer has no embed sources configured by default. An embed expression cannot read files or fetch remote content unless the host supplies a source.
