ASTTemplateParser 2.0.8
dotnet add package ASTTemplateParser --version 2.0.8
NuGet\Install-Package ASTTemplateParser -Version 2.0.8
<PackageReference Include="ASTTemplateParser" Version="2.0.8" />
<PackageVersion Include="ASTTemplateParser" Version="2.0.8" />
<PackageReference Include="ASTTemplateParser" />
paket add ASTTemplateParser --version 2.0.8
#r "nuget: ASTTemplateParser, 2.0.8"
#:package ASTTemplateParser@2.0.8
#addin nuget:?package=ASTTemplateParser&version=2.0.8
#tool nuget:?package=ASTTemplateParser&version=2.0.8
AST Template Parser
A blazing-fast, security-hardened template engine for .NET with HTML-like syntax and 2000x faster cached rendering.
โก Performance at a Glance
| Scenario | Speed | Comparison |
|---|---|---|
| Cached Render | ~0.001ms | ๐ฅ 2000x faster |
| Data-Aware Cache | ~0.01ms | ๐ 200x faster |
| Normal Render | ~2ms | Baseline |
โจ Features
Core
- ๐ High Performance - 1,000,000+ cached renders/second
- ๐ Enterprise Security - XSS protection, loop limits, property blocking
- ๐งฉ Component System -
<Element>,<Block>,<Data>,<Nav>components - ๐ Layout System - Master layouts with sections and slots
Caching (v2.0.5)
- โก Render Caching - Cache rendered output for instant response
- ๐ Auto File Invalidation - Cache updates when template file changes
- ๐ Data-Aware Caching - Auto-invalidate when variables change
- โฐ Time-Based Expiration - Optional cache TTL
Template Features
- ๐ฏ Indexers -
{{ items[0] }},{{ dict["key"] }} - ๐งช Filters -
{{ Name | uppercase }},{{ Price | currency }} - ๐ Global Variables - Set once, use everywhere
- ๐ Fragments -
<Define>and<Render>for recursion
Performance Optimizations (v2.0.6)
- ๐งฎ NCalc Expression Caching - Parsed expression trees cached & reused (~2.5x faster)
- โก ICollection Fast Path - O(1) count check instead of enumerator allocation (~10x faster)
- ๐ Adaptive StringBuilder Pool - Tiered small/large pools with template size hints
- ๐ Data Hash Dirty Flag - Skip hash recomputation when variables unchanged (~50x faster)
- ๐๏ธ Pre-allocated Variable Merge - Capacity estimation eliminates dictionary resizing
- ๐ .NET 9.0 & 10.0 Support - Full support for latest .NET frameworks
Block Parser & Mixed Content (NEW in v2.0.8)
- ๐งฑ Block Parser - Extract
<Block>components from page templates withParseBlocks() - ๐ Mixed Content Parsing -
ParseTemplateSegments()preserves both blocks AND raw HTML in order - โก Compiled Regex - Pre-compiled
RegexOptions.Compiledfor ~3-5x faster parsing - ๐ Path Traversal Protection -
ValidatePath()prevents directory escape attacks - ๐ก๏ธ Component Validation - Blocks
../and:in component paths
๐ฆ Installation
# NuGet Package Manager
Install-Package ASTTemplateParser
# .NET CLI
dotnet add package ASTTemplateParser
๐ Quick Start
using ASTTemplateParser;
var engine = new TemplateEngine();
engine.SetPagesDirectory("./pages");
// Set data
engine.SetVariable("User", new { Name = "Alice", Role = "Admin" });
// โก Cached render - 2000x faster on repeat calls!
string html = engine.RenderCachedFile("dashboard.html", "dashboard", includeDataHash: true);
โก Caching Guide (NEW!)
Static Pages (Fastest)
// Cache indefinitely until file changes
string about = engine.RenderCachedFile("about.html", "about");
string faq = engine.RenderCachedFile("faq.html", "faq");
User-Specific Pages (Smart Cache)
// Auto-invalidate when variables change
engine.SetVariable("User", currentUser);
engine.SetVariable("Cart", cartItems);
string dashboard = engine.RenderCachedFile(
"dashboard.html",
"dashboard",
includeDataHash: true // โฌ
๏ธ Magic! Data changes = new render
);
Time-Based Expiration
// Cache for 5 minutes
string news = engine.RenderCachedFile(
"news.html",
"news",
expiration: TimeSpan.FromMinutes(5)
);
Cache Management
// Invalidate specific cache
TemplateEngine.InvalidateCache("dashboard");
// Invalidate by prefix (e.g., all user caches)
TemplateEngine.InvalidateCacheByPrefix("user-");
// Clear all cache
TemplateEngine.ClearRenderCache();
// Get stats
var stats = TemplateEngine.GetRenderCacheStats();
Console.WriteLine($"Cached pages: {stats["TotalEntries"]}");
๐งฑ Block Parser (NEW in v2.0.8)
Parse Blocks from Page Templates
var engine = new TemplateEngine();
engine.SetPagesDirectory("./pages");
var blockParser = new BlockParser(engine);
// Extract <Block> components from page template
var blocks = blockParser.ParseBlocks("home");
foreach (var block in blocks)
{
Console.WriteLine($"{block.Order}: {block.Name} โ {block.ComponentPath}");
// 0: slider_un โ slider
// 1: about_un โ about/standard
// 2: blog_un โ blog
}
Mixed Content โ Blocks + Raw HTML
// Parse page template that has BOTH <Block> calls AND raw HTML
var segments = blockParser.ParseTemplateSegments("home");
foreach (var segment in segments)
{
if (segment.IsBlock)
{
// Render block via engine
var html = engine.RenderCachedFile(
"block/" + segment.Block.ComponentPath,
"block-" + segment.Block.ComponentPath);
output.AppendLine(html);
}
else if (segment.IsHtml)
{
// Raw HTML โ directly append
output.AppendLine(segment.RawHtml);
}
}
Cache Management
// Clear all block/segment caches
BlockParser.ClearCache();
// Clear specific template cache
BlockParser.ClearCache("home");
// Monitor cache
Console.WriteLine($"Block cache: {BlockParser.CacheCount}");
Console.WriteLine($"Segment cache: {BlockParser.SegmentCacheCount}");
๐ Template Syntax
Variables & Indexers
{{Name}}
{{User.Address.City}}
{{Items[0].Title}}
{{Config["apiKey"]}}
Filters
{{ Name | uppercase }}
{{ Price | currency:"en-US" }}
{{ Created | date:"dd MMM yyyy" }}
{{ Description | truncate:100 }}
Conditionals
<If condition="IsLoggedIn">
<p>Welcome, {{User.Name}}!</p>
<ElseIf condition="Role == 'guest'">
<p>Hello, Guest!</p>
<Else>
<p>Please log in</p>
</If>
Loops
<ForEach var="product" in="Products">
<div class="card">
<h3>{{product.Name}}</h3>
<p>{{product.Price | currency}}</p>
</div>
</ForEach>
Components
<Element component="button">
<Param name="text" value="Click Me" />
<Param name="type" value="primary" />
</Element>
<Block component="hero">
<Param name="title" value="{{PageTitle}}" />
</Block>
๐ Security
var security = new SecurityConfig {
MaxLoopIterations = 500, // DoS protection
MaxRecursionDepth = 5, // Stack protection
HtmlEncodeOutput = true, // XSS protection
BlockedPropertyNames = new HashSet<string> { "Password", "Secret" }
};
var engine = new TemplateEngine(security);
๐ Performance Benchmarks
| Operation | Speed | Notes |
|---|---|---|
| Cache Hit (Static) | ~0.001ms | 1M+ ops/sec |
| Cache Hit (Data Hash) | ~0.003ms | 300K+ ops/sec |
| Normal Render | ~2ms | 500 ops/sec |
| Property Access | ~0.00008ms | 12M+ ops/sec |
| NCalc Expression (cached) | ~0.2ms | 2.5x faster than uncached |
| IsTruthy (ICollection) | ~0.001ms | 10x faster than enumerator |
| Data Hash (unchanged) | ~0.001ms | 50x faster with dirty flag |
Tested on .NET 8.0+ / Intel i7 / Windows 11
๐ฏ Supported Frameworks
| Framework | Version | Status |
|---|---|---|
| .NET Standard | 2.0 | โ Supported |
| .NET Framework | 4.8 | โ Supported |
| .NET | 6.0 | โ Supported |
| .NET | 8.0 | โ Supported |
| .NET | 9.0 | โ Supported |
| .NET | 10.0 | โ Supported |
๐ Global Variables
// Set once at startup
TemplateEngine.SetGlobalVariable("SiteName", "My Website");
TemplateEngine.SetGlobalVariable("Year", DateTime.Now.Year);
// Available in ALL templates automatically!
// No need to call SetVariable() every time
๐ง API Reference
Block Parser Methods
| Method | Description |
|---|---|
ParseBlocks() |
Extract <Block> tags from page template |
ParseTemplateSegments() |
โญ NEW - Parse blocks + raw HTML segments |
ParseBlocksFromContent() |
Parse from string content |
ParseSegmentsFromContent() |
Parse segments from string |
ClearCache() |
Clear all block & segment caches |
CacheCount |
Block cache entry count |
SegmentCacheCount |
Segment cache entry count |
Rendering Methods
| Method | Description |
|---|---|
Render() |
Normal template rendering |
RenderFile() |
Render from file |
RenderCached() |
Cached string template |
RenderCachedFile() |
โญ Recommended - Cached file render |
Cache Methods
| Method | Description |
|---|---|
InvalidateCache(key) |
Remove specific cache |
InvalidateCacheByPrefix(prefix) |
Remove matching caches |
ClearRenderCache() |
Clear all caches |
HasCachedRender(key) |
Check cache exists |
RenderCacheCount |
Get cache count |
GetRenderCacheStats() |
Get detailed stats |
๐ License
MIT License - see LICENSE for details.
๐ Links
Made with โค๏ธ for the .NET community
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 is compatible. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETFramework 4.8
- NCalc.NetCore (>= 1.0.1)
-
.NETStandard 2.0
- NCalc.NetCore (>= 1.0.1)
-
net10.0
- NCalc.NetCore (>= 1.0.1)
-
net6.0
- NCalc.NetCore (>= 1.0.1)
-
net8.0
- NCalc.NetCore (>= 1.0.1)
-
net9.0
- NCalc.NetCore (>= 1.0.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 2.0.8 | 44 | 2/15/2026 |
| 2.0.7 | 83 | 2/10/2026 |
| 2.0.6 | 95 | 2/10/2026 |
| 2.0.5 | 78 | 2/9/2026 |
| 2.0.4 | 79 | 2/9/2026 |
| 2.0.3 | 87 | 1/21/2026 |
| 2.0.2 | 83 | 1/20/2026 |
| 2.0.0 | 94 | 1/20/2026 |
| 1.0.45 | 96 | 1/19/2026 |
| 1.0.43 | 87 | 1/19/2026 |
| 1.0.42 | 81 | 1/19/2026 |
| 1.0.41 | 84 | 1/19/2026 |
| 1.0.40 | 85 | 1/19/2026 |
| 1.0.39 | 95 | 1/17/2026 |
| 1.0.38 | 81 | 1/15/2026 |
| 1.0.37 | 89 | 1/15/2026 |
| 1.0.36 | 91 | 1/15/2026 |
| 1.0.35 | 86 | 1/15/2026 |
| 1.0.33 | 87 | 1/14/2026 |
| 1.0.32 | 80 | 1/14/2026 |
v2.0.8 - (February 15, 2026)
- ADDED: Mixed Content Parsing - ParseTemplateSegments() method for page templates with both Block calls and raw HTML.
- ADDED: TemplateSegment class with IsBlock/IsHtml helpers for easy segment type checking.
- ADDED: ParseSegmentsFromContent() for parsing template strings directly.
- ADDED: SegmentCacheCount property for monitoring segment cache usage.
- PERFORMANCE: Pre-compiled static Regex (RegexOptions.Compiled) for block and param parsing (~3-5x faster regex).
- PERFORMANCE: Segment results cached via ConcurrentDictionary (same pattern as ParseBlocks).
- PERFORMANCE: OrdinalIgnoreCase on parameter dictionaries for consistent case-insensitive lookups.
- SECURITY: Path traversal protection - ValidatePath() prevents reading files outside allowed directories.
- SECURITY: Component path validation - blocks ../ and : characters in component attributes.
- IMPROVED: ClearCache() now clears both block and segment caches simultaneously.
v2.0.6 - (February 10, 2026)
- ADDED: .NET 9.0 and .NET 10.0 target framework support.
- PERFORMANCE: NCalc expression caching - parsed LogicalExpression trees are now cached and reused (~2.5x faster repeated expressions).
- PERFORMANCE: Adaptive StringBuilder pooling with tiered small/large pools and template size hints.
- PERFORMANCE: ICollection fast path in IsTruthy - avoids enumerator allocation for List, Array, Dictionary (~10x faster).
- PERFORMANCE: Data hash dirty flag - skips hash recomputation when variables haven't changed (~50x faster cache hits).
- PERFORMANCE: Pre-allocated variable merge with capacity estimation - eliminates dictionary resizing.
- PERFORMANCE: Eliminated .ToString() overhead in data hash computation - uses GetHashCode() directly.
v2.0.5 - (February 9, 2026)
- ADDED: High-Performance Render Template Caching (RenderCachedFile, RenderCached).
- ADDED: Data-aware caching with includeDataHash parameter for auto-invalidation.
- ADDED: Automatic file-based cache invalidation via timestamp detection.
- ADDED: Support for searching both Pages and Components directories in RenderCachedFile.
- ADDED: Optional time-based cache expiration (TimeSpan).
- ADDED: Cache management APIs: InvalidateCache, InvalidateCacheByPrefix, ClearRenderCache.
- ADDED: Cache statistics via GetRenderCacheStats() for monitoring.
- PERFORMANCE: 2000x faster repeated renders with cache hit (~0.001ms vs ~2ms).
v2.0.3 - (January 21, 2026)
- ADDED: Template Filters with Pipe syntax (e.g. {{ Name | uppercase }}).
- ADDED: Built-in filters: uppercase, lowercase, date, currency.
- ADDED: Support for Filter Arguments (e.g. {{ Price | currency:"bn-BD" }}).
- ADDED: Custom Filter Registration via TemplateEngine.RegisterFilter().
- IMPROVED: Filter execution performance with cached delegates.
v2.0.2 - (January 20, 2026)
- FIXED: Resolved "Unsafe expression" errors by making SecurityConfig less restrictive by default.
- FIXED: Improved regex for safe characters in expressions (bracket and quote support).
- IMPROVED: Added detailed reason to TemplateSecurityException for easier debugging.
- IMPROVED: Added support for IList and native Array indexing (e.g. item[0]).
- IMPROVED: Exposed Security property on TemplateEngine for instance-level configuration.
v2.0.1 - (January 20, 2026)
- ADDED: High-performance Indexer Support (item[key]).
- ADDED: Compiled delegate caching for indexers for maximum speed.
- ADDED: Support for dynamic key resolution in templates.
- IMPROVED: Expression evaluation robustness.
- SECURITY: Enhanced indexer validation with BlockedPropertyNames.