Skip to content

C0DK/Strongbars

Repository files navigation

Strongbars

Compile-time, type-safe, zero-runtime-error templates for .NET

NuGet Version

Why Strongbars?

Most template engines discover missing variables at runtime. Stronbars discovers them at compile time via a C# source generator. You get:

  • IntelliSense for every template parameter
  • Build errors instead of blank or broken output
  • No reflection, no dynamic compilation, no runtime failures
  • Very fast templating — ~3–5× faster than the next best engine, up to 330× faster than others (see benchmarks)

Think of it as “Razor without the runtime” or “Mustache with a compiler”.

Motivation

I developed Strongbars after using string interpolation for my various micro-webapps. Having used a variety of different templating engines they are all very dependent on dynamically typed input and are in my opinion both way too extensive and too difficult to debug. I was unable to find a templating engine that gave me the compile-time validation so string interpolation seemed to be the only way. However this left me with a lot of HTML code in the middle of a c# file. Not super good developer UX. I missed dedicated files for the templates, but were unable to find any tool that fit my style. This gave me the best of both worlds.

Install

dotnet add package Strongbars

How it works

Add something like this to your *.csproj:

  <ItemGroup>
    <AdditionalFiles Include="Pages/*.html" StrongbarsNamespace="Sample.Pages" />
  </ItemGroup>

Every file in Pages becomes a strongly-typed class. Hello.html:

<p> 
    Hello {{ firstName }} {{ lastName }}
</p>

Build → the generator produces:

public class Name
{
    public Name(string firstName, string lastName) {
      ...
    }

    public string Render() => ...
}

Usage:

using Sample.Pages

var template = new Hello(firstName: "Alex", lastName: "Smith");
Console.WriteLine(template.Render());

Output:

<p>
    Hello Alex Smith
</p>

You could also use the same variable multiple times, i.e:

Hello.html:

<p> 
    Hello {{ firstName }} {{ lastName }} - {{ firstName }} is a pretty name!
</p>

See example for a complete(r) example.

Loops?

Handlebars.js and similar frameworks have loops and other helpers. They are not supported by design. Strongbars encourage high modularity and truely logic less templating. Instead, Strongbars allow a syntax for defining a variable as an array, which will then be concatenatted. This forces you to create very narrow and modular files, for better or worse (IMO better). I.e to implement the same code as in the link you need two files:

PeopleList.html:

<ul class="people_list">
  {{ ..items }}
</ul>

ListItem.html:

<li>
  {{value}}
</li>

Which can be used like this:

var template = new PeopleList([
    new ListItem("Yehuda Katz"),
    new ListItem("Alan Johnson"),
    new ListItem("Charles Jolley"),
]);

Warning

If a template has a variable of the same name multiple places with both .. and without, it will fail.

Conditionals

Strongbars supports inline conditional blocks using {% if %} and {% unless %} tags.

{% if %}

Renders the block content when the condition is true. An optional {% else %} branch is rendered when the condition is false.

Message.html:

<div class="message {% if urgent %}urgent{% else %}normal{% end %}">{{message}}</div>

Build → the generator produces a bool urgent and TemplateArgument message constructor parameter:

var urgent = new Message(urgent: true,  message: "Server is down!");
var normal = new Message(urgent: false, message: "All systems nominal.");

Output:

<div class="message urgent">Server is down!</div>
<div class="message normal">All systems nominal.</div>

{% unless %}

The inverse of {% if %} — renders the block content when the condition is false. Mirrors {{#unless}} in Handlebars. An optional {% else %} branch is rendered when the condition is true.

Subscription.html:

<p>{% unless premium %}Free tier{% else %}Premium member{% end %}</p>
var free    = new Subscription(premium: false); // → <p>Free tier</p>
var premium = new Subscription(premium: true);  // → <p>Premium member</p>

Both tags can be combined freely in the same template, and they compose naturally with {{ variable }} interpolation.

Note

If you still prefer to keep conditional logic in your C# code (e.g. for a proper if/else fallback), optional variables still work well for that:

var template = new Entry(
    author
    ? new EntryAuthor(firstName: "Casper", lastName: "Bang")
    : null
);

Warning

If a variable is both marked as optional and not optional it will fallback to being not-optional.

Current feature set

  • Variable injection: {{foo}}
  • Iterable variables: a .. preceding a variable name, i.e {{..foo}}
  • Optional variables: a ? after the variable name, i.e {{foo?}} (Can be combined with iterables)
  • Conditional blocks: {% if condition %}...{% else %}...{% end %} — renders first branch when bool is true, optional else branch otherwise
  • Inverse conditional blocks: {% unless condition %}...{% else %}...{% end %} — renders first branch when bool is false, optional else branch otherwise
  • Whitespace inside delimiters is ignored
  • Works in any text-based file (HTML, JSON, SQL, etc.)
  • Generated code is internal by default; visibility can be tweaked via item metadata

Roadmap

  • Automatic HTML-encoding for .html files
  • Custom delimiters via .csproj property

Benchmarks

As templates are converted at compile time to pre-computed literal segments, there is zero runtime parsing, and it is really fast.

Compared to other framesworks with a bunch of different templates:

BenchmarkDotNet v0.15.8 · .NET 10.0.4 · Intel Xeon 2.10 GHz

Engine ListItem SimpleGreeting ArticleCard ProfileCard UserProfile FullPage
Strongbars 27 ns 57 ns 101 ns 109 ns 134 ns 2,340 ns
Fluid (Liquid) 212 ns 273 ns 448 ns 540 ns 625 ns 7,878 ns
Handlebars.Net 236 ns 334 ns 478 ns 489 ns 662 ns 11,439 ns
Stubble (Mustache) 553 ns 736 ns 1,381 ns 1,413 ns 1,846 ns 35,189 ns
Scriban 8,879 ns 8,977 ns 9,399 ns 9,475 ns 9,661 ns 24,763 ns

Strongbars is ~3–5× faster than Fluid and Handlebars, ~13× faster than Stubble, and ~90–330× faster than Scriban — measured across templates ranging from a one-variable greeting to a full HTML page with 20+ conditionals.

See full results.

You can add additional templates to the benchmarking folder, and simply run dotnet run -c Release --project Strongbars.Benchmarks.

Thanks to

Strongly inspired and forked from ConstEmbed

About

minimal tooling to turn html.hbs files into strongly typed builder classes

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors