15 releases (4 breaking)
| 0.5.3 | Aug 20, 2025 |
|---|---|
| 0.5.2 | Aug 19, 2025 |
| 0.4.1 | Aug 19, 2025 |
| 0.3.4 | Aug 19, 2025 |
| 0.1.4 | Aug 18, 2025 |
#56 in Template engine
429 downloads per month
Used in zip_templates
290KB
4.5K
SLoC
๐ฎ Mystical-Runic - High-Performance Template Engine
Zero-dependency, high-performance templating engine for Rust with enterprise-grade features
Mystical-Runic is a high-performance templating engine that combines the simplicity of Mustache syntax with powerful enterprise features. Built for production use with zero external dependencies, comprehensive security, and exceptional performance.
๐ Documentation
| Type | Description | Lien |
|---|---|---|
| ๐ฆ API Reference | Complete technical documentation | docs.rs/mystical-runic |
| ๐ซ๐ท Guide Utilisateur | Documentation franรงaise avec tutoriels | Documentation HTML |
| ๐ Quick Start | cargo doc --open --all-features |
Documentation locale |
| ๐ฏ Examples | Real-world demos and usage examples | examples/ |
๐ก Tip: Start with the French user guide for tutorials and examples, then use the API reference for technical details.
โจ Features
๐ฏ Core Template Engine
- ๐ญ Dual API Style: Choose between conventional (
TemplateEngine) or mystical (RuneEngine) naming - ๐ฏ Simple API: Clean, intuitive interface for Rust developers
- ๐ Deep Object Navigation: Unlimited depth dot notation (e.g.,
{{user.profile.stats.level}}) - ๐ Nested Templates: Full support for nested loops and recursive template includes
- ๐๏ธ Template Inheritance: Advanced layout system with nested inheritance and
{{super}} - ๐ฆ Reusable Macros: Define and reuse template components with parameters
๐ง Filters & Transformations
- ๐ง Powerful Filters: Built-in filters like
upper,lower,currency,truncatewith chaining support - ๐ข Advanced Math Filters: Mathematical operations with
add,multiply,divide,percentage,round - ๐จ Custom Filter API: Register your own filters for domain-specific transformations
- ๐ Internationalization (i18n): Multi-language support with
{{t "key"}}syntax and locale switching - ๐ Smart Pluralization: Automatic plural forms with
{{plural count "item" "items"}}
๐ Security & Quality
- ๐ Security First: XSS-safe by default with comprehensive HTML escaping
- ๐ก๏ธ Path Traversal Protection: Enterprise-grade security preventing
../attacks - ๐ Enterprise Security: Threat classification and audit logging (v0.5.1)
- ๐งช Well Tested: 204+ tests with comprehensive coverage following strict TDD methodology
- ๐ฆ Zero Dependencies: Pure Rust implementation with no external dependencies
โก Performance & Monitoring
- โก High Performance: Template caching, bytecode compilation, parallel processing
- ๐ Performance Monitoring: Advanced metrics collection and optimization (v0.5.1)
- ๐ฆ Modern Rust: Rust 2021 edition with 1.74.0+ MSRV, future Rust 2024 ready
๐ ๏ธ Developer Experience
- ๐ Enhanced Error Messages: Line/column numbers with helpful suggestions and context (v0.4.0)
- ๐ Template Debugging: Step-through debugging with variable tracking and execution insights (v0.4.0)
- ๐ฅ Hot Reload: Development-time template reloading for faster iteration cycles (v0.4.0)
- ๐ป IDE Integration: Full Language Server Protocol support with auto-completion, syntax highlighting, error squiggles (v0.4.1)
๐ Ecosystem Integration (v0.5.0+)
- ๐ Async Support: Non-blocking template rendering for high-performance web applications
- ๐ Web Framework Integration: First-class support for Axum, Warp, and Actix-web
- ๐ธ๏ธ WASM Ready: Browser-compatible template rendering with JavaScript bindings
- ๐ ๏ธ CLI Tools: Command-line template processing with watching and batch operations
๐ Template Syntax
Core Features
- Variables:
{{name}}- HTML-escaped variable output for XSS protection - Raw HTML:
{{& html}}- Unescaped HTML output (use with caution) - Conditionals:
{{if condition}}...{{/if}}- Conditional rendering with comparison operators - Loops:
{{for item in items}}...{{/for}}- Iterate over arrays and objects - Includes:
{{include "template.html"}}- Template composition and reuse - Comments:
{{! comment }}- Template comments (not rendered) - Deep Access:
{{user.profile.stats.level}}- Unlimited depth object property access
Advanced Sorcery (v0.2.0)
- Sacred Inheritance:
{{extends "base.html"}}- Inherit the power of ancestral templates - Mystical Blocks:
{{block content}}...{{/block}}- Define regions of power in your layouts - Ancestral Wisdom:
{{super}}- Channel the content of parent templates - Transformation Filters:
{{name|upper|truncate:10}}- Transform values with ancient filters - Reusable Spells (Macros):
{{macro spell(power)}}...{{/macro}}- Create reusable incantations - Spell Invocation:
{{spell("lightning")}}- Call upon your defined macros
Master Sorcery (v0.3.4) - The Advanced Features
- Nested Loop Mastery:
{{for category in shops}}{{for item in category.items}}...{{/for}}{{/for}}- Complex nested iterations with stack-based parsing - Recursive Includes: Templates can include other templates that include more templates - unlimited depth!
- Path Traversal Wards: Enterprise-grade protection against
../../../etc/passwdandC:\Windows\System32attacks - Multilingual Magic:
{{t "welcome" name=user}}- Full i18n with variable interpolation - Smart Plurals:
{{plural count "item" "items"}}- Automatic singular/plural forms - Mathematical Alchemy:
{{price|multiply:1.2|add:shipping|round:2|currency}}- Complex calculations with filter chaining - Custom Enchantments: Register your own filters with
engine.register_filter()
Global Sorcery (v0.3.0)
- Universal Translation:
{{t "welcome"}}- Speak all tongues with i18n support - Locale Switching: Switch between languages with
engine.set_locale("en") - Quantity Wisdom:
{{plural count "item" "items"}}- Smart pluralization magic - Mathematical Alchemy:
{{price|add:10|multiply:2|percentage}}- Advanced math transformations - Custom Enchantments:
engine.register_filter("reverse", |input, _| Ok(input.chars().rev().collect()))- Forge your own filters
Developer Experience (v0.4.0) - The Debugging Edition
- Enhanced Error Diagnostics:
ParseWithLocation- Precise line/column error reporting with context - Intelligent Suggestions: Template and variable name suggestions for typos
- Debug Mode:
engine.enable_debug_mode()- Variable tracking and execution step analysis - Template Debugging:
render_string_with_debug()- Step-through debugging with performance metrics - Hot Reload:
engine.enable_hot_reload()- Automatic template reloading during development - Developer-Friendly Errors: Stack traces for nested template errors with full context
IDE Integration (v0.4.1) - The Editor Edition
- Language Server Protocol:
parse_for_lsp()- Full LSP support for template editing - Auto-completion: Smart suggestions for variables, filters, and template syntax
- Syntax Highlighting: Rich syntax highlighting with error detection
- Hover Information: Contextual help and variable type information
- Go-to-Definition: Navigate to template includes and macro definitions
- Real-time Diagnostics: Live error checking with squiggly underlines
Ecosystem Integration (v0.5.0) - The Modern Web Edition
- Async Support:
render_string_async()- Non-blocking template rendering with tokio - Concurrent Rendering: Clone engines for parallel template processing
- Web Framework Integration:
- Axum:
engine.render_axum()- Direct HTML responses - Warp:
engine.render_warp()- Reply trait integration - Actix:
engine.render_actix()- HttpResponse integration
- Axum:
- WASM Compatibility:
WasmRuneEngine- Browser-ready template rendering - JavaScript Bindings:
engine.render_string(template, json)for web apps - CLI Tools: Command-line template processing utilities
process_template()- Direct string processingprocess_files()- File-based template renderingbatch_process()- Multiple template processingTemplateWatcher- File system watching with hot reload
- Configuration Management: TOML-based configuration loading
- Go to Definition:
get_definition_at_position()- Navigate to macro definitions
๐ Quick Start
๐ Complete setup guide: See our detailed installation documentation for comprehensive instructions and examples.
Installation
Basic Installation
[dependencies]
mystical-runic = "0.5.2"
With Ecosystem Integration Features (v0.5.0)
[dependencies]
# Async support for high-performance web apps
mystical-runic = { version = "0.5.2", features = ["async"] }
# Web framework integration
mystical-runic = { version = "0.5.2", features = ["web-frameworks"] }
# Or specific frameworks:
# mystical-runic = { version = "0.5.2", features = ["axum-integration"] }
# mystical-runic = { version = "0.5.2", features = ["warp-integration"] }
# mystical-runic = { version = "0.5.2", features = ["actix-integration"] }
# WASM browser compatibility
mystical-runic = { version = "0.5.2", features = ["wasm"] }
# CLI tools and utilities
mystical-runic = { version = "0.5.2", features = ["cli"] }
# All ecosystem features
mystical-runic = { version = "0.5.2", features = ["full"] }
Available Features:
| Feature | Description | Category |
|---|---|---|
async |
Async template rendering with Tokio | ๐ Performance |
axum-integration |
Axum web framework support | ๐ Web Frameworks |
warp-integration |
Warp web framework support | ๐ Web Frameworks |
actix-integration |
Actix-web framework support | ๐ Web Frameworks |
web-frameworks |
All web framework integrations | ๐ Web Frameworks |
wasm |
WebAssembly browser compatibility | ๐ธ๏ธ Browser/WASM |
cli |
Command-line tools and utilities | ๐ ๏ธ Developer Tools |
full |
All ecosystem integration features | ๐ฆ Complete Package |
Basic Usage - Choose Your Style! ๐ญ
๐ข Conventional Style
Perfect for corporate environments, team projects, and those who prefer explicit naming:
use mystical_runic::{TemplateEngine, TemplateContext, TemplateValue};
let mut engine = TemplateEngine::new("templates");
let mut context = TemplateContext::new();
// Set variables in your template context
context.set("hero", TemplateValue::String("Rust Developer".to_string()));
context.set("level", TemplateValue::Number(99));
context.set("has_coffee", TemplateValue::Bool(true));
let result = engine.render_string(
"Hello {{hero}} of level {{level}}! {{if has_coffee}}โ Ready to work!{{/if}}",
&context
).unwrap();
๐ฎ Mystical Style (Themed)
For the adventurous, creative projects, and those who enjoy a touch of magic:
use mystical_runic::{RuneEngine, RuneScroll, RuneSymbol};
// Summon the ancient engine from the template realm
let mut engine = RuneEngine::new("sacred_scrolls");
let mut scroll = RuneScroll::new();
// Inscribe your desires upon the scroll
scroll.set("hero", RuneSymbol::String("Mystical Sorcerer".to_string()));
scroll.set("level", RuneSymbol::Number(99));
scroll.set("has_coffee", RuneSymbol::Bool(true));
// Speak the incantation and witness the transformation
let result = engine.render_string(
"Behold! {{hero}} of level {{level}} embarks upon their quest! {{if has_coffee}}โ{{/if}}",
&scroll
).unwrap();
๐ก Pro Tip: Both styles are completely interchangeable! Use whichever feels right for your project. You can even mix them in the same codebase - they're just aliases for the same underlying types.
Advanced Example: Character Sheet Generator
use mystical_runic::{RuneEngine, RuneScroll, RuneSymbol};
use std::collections::HashMap;
let mut engine = RuneEngine::new(".");
let mut scroll = RuneScroll::new();
// Create a magical character
let mut character = HashMap::new();
character.insert("name".to_string(), RuneSymbol::String("Gandalf the Grey".to_string()));
character.insert("class".to_string(), RuneSymbol::String("Wizard".to_string()));
character.insert("level".to_string(), RuneSymbol::Number(85));
character.insert("mana".to_string(), RuneSymbol::Number(9999));
character.insert("has_staff".to_string(), RuneSymbol::Bool(true));
scroll.set("character", RuneSymbol::Object(character));
// โ๏ธ Create spell list
let spells = vec![
create_spell("Fireball", 50, "๐ฅ"),
create_spell("Lightning Bolt", 75, "โก"),
create_spell("Ice Shard", 40, "โ๏ธ"),
];
scroll.set("spells", RuneSymbol::Array(spells));
let character_sheet = r#"
๐งโโ๏ธ Name: {{character.name}}
๐ Class: {{character.class}} (Level {{character.level}})
๐ฎ Mana: {{character.mana}}
{{if character.has_staff}}
๐ช Equipment: Magical Staff of Power
{{/if}}
โก KNOWN SPELLS:
{{for spell in spells}}
{{spell.icon}} {{spell.name}} - Power: {{spell.damage}}
{{/for}}
"#;
let result = engine.render_string(character_sheet, &scroll).unwrap();
println!("{}", result);
fn create_spell(name: &str, damage: i64, icon: &str) -> RuneSymbol {
let mut spell = HashMap::new();
spell.insert("name".to_string(), RuneSymbol::String(name.to_string()));
spell.insert("damage".to_string(), RuneSymbol::Number(damage));
spell.insert("icon".to_string(), RuneSymbol::String(icon.to_string()));
RuneSymbol::Object(spell)
}
Deep Dot Notation Example
use mystical_runic::{RuneEngine, RuneScroll, RuneSymbol};
use std::collections::HashMap;
let mut engine = RuneEngine::new(".");
let mut scroll = RuneScroll::new();
// Create deeply nested game data structure
let mut stats = HashMap::new();
stats.insert("level".to_string(), RuneSymbol::Number(42));
stats.insert("health".to_string(), RuneSymbol::Number(100));
stats.insert("mana".to_string(), RuneSymbol::Number(75));
let mut equipment = HashMap::new();
equipment.insert("weapon".to_string(), RuneSymbol::String("Mystical Sword".to_string()));
equipment.insert("armor".to_string(), RuneSymbol::String("Dragon Scale".to_string()));
let mut character = HashMap::new();
character.insert("name".to_string(), RuneSymbol::String("Aragorn".to_string()));
character.insert("class".to_string(), RuneSymbol::String("Ranger".to_string()));
character.insert("stats".to_string(), RuneSymbol::Object(stats));
character.insert("equipment".to_string(), RuneSymbol::Object(equipment));
let mut game_data = HashMap::new();
game_data.insert("character".to_string(), RuneSymbol::Object(character));
scroll.set("game", RuneSymbol::Object(game_data));
// Use deep dot notation to access nested values
let template = r#"
๐ฎ GAME CHARACTER SHEET ๐ฎ
๐ค Name: {{game.character.name}}
๐ญ Class: {{game.character.class}}
๐ STATS:
โค๏ธ Health: {{game.character.stats.health}}
๐ Mana: {{game.character.stats.mana}}
โญ Level: {{game.character.stats.level}}
โ๏ธ EQUIPMENT:
{{if game.character.equipment.weapon}}
๐ก๏ธ Weapon: {{game.character.equipment.weapon}}
{{/if}}
{{if game.character.equipment.armor}}
๐ก๏ธ Armor: {{game.character.equipment.armor}}
{{/if}}
{{if game.character.stats.level}}
๐ Status: {{if game.character.stats.health}}Combat Ready{{/if}}
{{/if}}
"#;
let result = engine.render_string(template, &scroll).unwrap();
println!("{}", result);
// ๐ฅ NEW v0.4.0: Debug Mode for Development
engine.enable_debug_mode();
let debug_result = engine.render_string_with_debug(template, &scroll).unwrap();
println!("Rendered: {}", debug_result.output);
println!("Variables accessed: {:?}", debug_result.debug_info.variables_accessed);
println!("Execution time: {}ms", debug_result.debug_info.performance_metrics.total_time_nanos / 1_000_000);
IDE Integration Example (v0.4.1)
use mystical_runic::{RuneEngine, RuneScroll, RuneSymbol};
let mut engine = RuneEngine::new(".");
let mut context = RuneScroll::new();
context.set_string("user_name", "Alice");
context.set_number("user_level", 42);
let template = r#"
{{macro greeting(name, level)}}
<h1>Hello {{name}}! Level: {{level}}</h1>
{{/macro}}
{{greeting(user_name, user_level)}}
{{if user_level}}
{{user_name|upper}} is ready!
{{/if}}
"#;
// ๐ NEW v0.4.1: Language Server Protocol Support
let lsp_info = engine.parse_for_lsp(template, "greeting.html").unwrap();
println!("Variables found: {:?}", lsp_info.variables);
println!("Macros found: {:?}", lsp_info.macros);
// ๐ก NEW v0.4.1: Auto-completion at cursor position
let position = 95; // Position in "{{user_na|"
let completions = engine.get_completions_at_position(template, position, &context).unwrap();
for completion in completions {
println!("Suggestion: {} ({})", completion.label, completion.completion_type);
}
// ๐จ NEW v0.4.1: Syntax highlighting tokens
let tokens = engine.tokenize_for_syntax_highlighting(template).unwrap();
for token in tokens.iter().take(5) {
println!("Token: '{}' ({})", token.content, token.token_type);
}
// ๐จ NEW v0.4.1: Real-time error diagnostics
let invalid_template = "{{name}} {{unknown_variable}} {{name|nonexistent_filter}}";
let diagnostics = engine.get_diagnostics_for_editor(invalid_template, &context).unwrap();
for diagnostic in diagnostics {
println!("โ ๏ธ {}: {} (line {})", diagnostic.severity, diagnostic.message, diagnostic.line);
}
// โน๏ธ NEW v0.4.1: Hover information
let hover_position = 50; // Position over a variable
if let Ok(hover_info) = engine.get_hover_info_at_position(template, hover_position, &context) {
println!("Hover: {} ({}) = {}", hover_info.variable_name, hover_info.variable_type, hover_info.current_value);
}
// ๐ NEW v0.4.1: Go to definition
let macro_position = 200; // Position over a macro call
if let Ok(definition) = engine.get_definition_at_position(template, macro_position) {
println!("Definition: {} at line {} column {}", definition.name, definition.line, definition.column);
}
Ecosystem Integration Examples (v0.5.0)
Async Template Rendering
use mystical_runic::{RuneEngine, RuneScroll, AsyncTemplateEngine};
use tokio;
#[tokio::main]
async fn main() {
let mut engine = RuneEngine::new("templates");
let mut context = RuneScroll::new();
context.set_string("user", "Async Wizard");
// Non-blocking template rendering
let result = engine.render_string_async(
"Hello {{user}}! Processing your request...",
&context
).await.unwrap();
println!("{}", result);
}
Web Framework Integration
Axum Integration
use axum::{response::Html, routing::get, Router};
use mystical_runic::{RuneEngine, RuneScroll, AxumTemplateEngine};
async fn render_page(mut engine: RuneEngine) -> Result<Html<String>, String> {
let mut context = RuneScroll::new();
context.set_string("title", "My Axum App");
engine.render_axum("<h1>{{title}}</h1>", &context)
.await
.map_err(|e| e.to_string())
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| render_page(RuneEngine::new("templates"))));
// Serve your app...
}
WASM Browser Integration
use mystical_runic::WasmRuneEngine;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn render_in_browser() -> Result<String, JsValue> {
let mut engine = WasmRuneEngine::new();
engine.enable_console_logging(true);
let template = r#"
<div class="user-card">
<h2>{{user.name}}</h2>
<p>Level: {{user.level}}</p>
</div>
"#;
let context_json = r#"{"user": {"name": "Web Wizard", "level": 42}}"#;
engine.render_string(template, context_json)
}
CLI Tools Integration
use mystical_runic::{process_template, process_files, batch_process};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Direct template processing
let template = "Hello {{name}}!";
let data = r#"{"name": "CLI User"}"#;
let result = process_template(template, data)?;
println!("{}", result);
// File-based processing
let output = process_files("template.html", "data.json")?;
println!("File result: {}", output);
// Batch processing
let templates = vec!["template1.html", "template2.html"];
let context_json = r#"{"theme": "dark", "version": "v0.5.0"}"#;
let results = batch_process(templates, context_json)?;
for (i, result) in results.iter().enumerate() {
println!("Template {}: {}", i + 1, result);
}
Ok(())
}
๐ฎ Complete Real-World Demo Application
Experience ALL features of Mystical-Runic v0.5.0 with our comprehensive demonstration application!
# Run the complete feature showcase
cd examples/real_world_demo
./run_demo.sh
# OR manually
cargo run
๐ What the Demo Showcases
Our demo application is a full-featured e-commerce/blog site that demonstrates every single feature:
- ๐ NEW v0.3.4: Nested loops with complex data structures (categories โ products)
- ๐ NEW v0.3.4: Recursive includes with 4 levels deep (profile โ stats โ preferences โ comments)
- ๐ก๏ธ NEW v0.3.4: Path traversal protection blocking
../../../etc/passwdattacks - ๐๏ธ Template inheritance with
base.htmlโshop.html - ๐ Full i18n with French/English translations
- ๐ Smart pluralization throughout the interface
- ๐ข Advanced math filters for pricing, taxes, discounts
- ๐จ Custom filters for encryption, markdown, dates
- ๐ฆ Reusable macros for product cards
- ๐ Deep dot notation accessing
user.profile.settings.theme - ๐ XSS protection with real attack demonstrations
- โก Performance features with benchmarking
๐ Demo Results
๐ฎ MYSTICAL-RUNIC v0.3.4 - DรMONSTRATION COMPLรTE!
โ
Main template rendered successfully! (10KB+ HTML)
โ
Nested loops work perfectly!
โ
Nested includes work perfectly!
โ
All path traversal attempts blocked!
โ
XSS protection working
โ
Rendered 100 times in 1-2ms
โ
HTML file generated: output_demo.html
๐ All 173+ tests pass! Production ready!
๐ฏ Generated Output
The demo creates output_demo.html - a complete working website showcasing:
- Clean styling with responsive design
- Real e-commerce functionality simulation
- Complex nested data visualization
- Multi-language interface
- Security feature demonstrations
- Performance metrics display
๐ Location: examples/real_world_demo/ - Complete application with 7+ templates, realistic data, and full documentation.
๐ฐ Template Inheritance (v0.2.0)
Create sophisticated layouts with template inheritance:
<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
<title>{{block title}}My Site{{/block}}</title>
</head>
<body>
<header>{{block header}}Default Header{{/block}}</header>
<main>{{block content}}{{/block}}</main>
<footer>{{block footer}}ยฉ 2024 My Site{{/block}}</footer>
</body>
</html>
<!-- admin.html -->
{{extends "base.html"}}
{{block title}}Admin Panel - {{block page_title}}{{/block}}{{/block}}
{{block content}}
<div class="admin-layout">
<nav>{{block sidebar}}Default Sidebar{{/block}}</nav>
<main>{{block admin_content}}{{/block}}</main>
</div>
{{/block}}
<!-- admin_users.html -->
{{extends "admin.html"}}
{{block page_title}}User Management{{/block}}
{{block admin_content}}
<h1>Users</h1>
{{for user in users}}
<div class="user-card">{{user.name}} - {{user.role}}</div>
{{/for}}
{{/block}}
๐ง Powerful Filters (v0.2.0)
Transform your data with built-in filters:
<h1>{{title|upper}}</h1> <!-- HELLO WORLD -->
<p>{{description|lower}}</p> <!-- hello world -->
<span>${{price|currency}}</span> <!-- $12.99 -->
<div>{{content|truncate:50}}</div> <!-- Truncated text... -->
<time>{{date|date:"Y-m-d"}}</time> <!-- 2024-01-15 -->
<!-- Chain multiple filters -->
<p>{{name|lower|capitalize}}</p> <!-- John Doe -->
<span>{{text|strip|truncate:20|upper}}</span> <!-- TRIMMED TEXT... -->
๐ฆ Reusable Macros (v0.2.0)
Create reusable template components:
<!-- Define macros -->
{{macro button(text, type="button", class="btn")}}
<button type="{{type}}" class="{{class}}">{{text}}</button>
{{/macro}}
{{macro card(title, content, class="card")}}
<div class="{{class}}">
<h3 class="card-title">{{title}}</h3>
<div class="card-body">{{content}}</div>
</div>
{{/macro}}
{{macro user_card(user)}}
<div class="user-card">
<h4>{{user.name}}</h4>
<p>{{user.email}}</p>
{{if user.active}}
<span class="status active">Online</span>
{{/if}}
</div>
{{/macro}}
<!-- Use macros -->
{{button("Save", type="submit", class="btn btn-primary")}}
{{card("Welcome", "This is a welcome message", class="card highlight")}}
{{for user in users}}
{{user_card(user)}}
{{/for}}
๐ Template Syntax Guide
Variables
<!-- Safe HTML escaping (default) -->
<p>{{user_input}}</p>
<!-- Raw HTML output (use with caution) -->
<div>{{& trusted_html}}</div>
<!-- Object properties -->
<span>{{user.name}} ({{user.email}})</span>
<!-- Deep nested properties -->
<div>Level: {{player.character.stats.level}}</div>
<p>{{config.database.connection.host}}:{{config.database.connection.port}}</p>
Conditionals
{{if user.is_admin}}
<button class="admin-panel">Admin Controls</button>
{{/if}}
{{if items}}
<ul class="item-list">
<!-- items exist -->
</ul>
{{/if}}
<!-- Deep conditionals -->
{{if user.settings.notifications.email.enabled}}
<p>Email notifications are on</p>
{{/if}}
{{if config.features.advanced.enabled}}
<div class="advanced-features">Advanced mode active</div>
{{/if}}
Truthiness Rules:
- Strings: non-empty = true, empty = false
- Numbers: non-zero = true, zero = false
- Booleans: as expected
- Arrays: non-empty = true, empty = false
- Objects: non-empty = true, empty = false
Loops
{{for product in products}}
<div class="product">
<h3>{{product.name}}</h3>
<p>Price: ${{product.price}}</p>
{{if product.on_sale}}
<span class="sale-badge">ON SALE!</span>
{{/if}}
</div>
{{/for}}
Template Includes
<!-- main.html -->
<!DOCTYPE html>
<html>
<head>
{{include "partials/head.html"}}
</head>
<body>
{{include "partials/header.html"}}
<main>{{content}}</main>
{{include "partials/footer.html"}}
</body>
</html>
Comments
{{! This comment will not appear in the output }}
<div>
{{!
Multi-line comments
are also supported
}}
<p>Visible content</p>
</div>
๐ Security Features
Mystical-Runic takes security seriously and provides multiple layers of protection:
XSS Prevention
let mut context = RuneScroll::new();
context.set_string("user_input", "<script>alert('xss')</script>");
let result = engine.render_string("{{user_input}}", &context).unwrap();
// Output: <script>alert('xss')</script>
Path Traversal Protection
// These will safely fail:
engine.render("../../../etc/passwd", &context); // โ Blocked
engine.render("..\\windows\\system32", &context); // โ Blocked
Template Injection Prevention
context.set_string("malicious", "{{admin_password}}");
let result = engine.render_string("{{malicious}}", &context).unwrap();
// Output: {{admin_password}} (literal text, not executed)
๐จ API Reference
RuneEngine (TemplateEngine)
let mut engine = RuneEngine::new("path/to/templates");
// Render from file
let result = engine.render("template.html", &context)?;
// Render from string
let result = engine.render_string("Hello {{name}}!", &context)?;
// Load template (with caching)
let template_content = engine.load_template("header.html")?;
RuneScroll (TemplateContext)
let mut scroll = RuneScroll::new();
// Set different value types
scroll.set_string("name", "value");
scroll.set_number("count", 42);
scroll.set_bool("active", true);
// Set complex values
scroll.set("array", RuneSymbol::Array(vec![...]));
scroll.set("object", RuneSymbol::Object(hashmap));
// Retrieve values
let value = scroll.get_string("name");
RuneSymbol (TemplateValue)
// Create different value types
let string_val = RuneSymbol::String("text".to_string());
let number_val = RuneSymbol::Number(42);
let bool_val = RuneSymbol::Bool(true);
let array_val = RuneSymbol::Array(vec![...]);
let object_val = RuneSymbol::Object(hashmap);
๐งช Testing
Run the comprehensive test suite:
# Run all tests
cargo test
# Run specific test categories
cargo test integration_tests
cargo test unit_tests
cargo test security_tests
# Run with output
cargo test -- --nocapture
Internationalization Example (v0.3.0)
use mystical_runic::{RuneEngine, RuneScroll, RuneSymbol};
use std::collections::HashMap;
let mut engine = RuneEngine::new("./templates");
let mut context = RuneScroll::new();
context.set("name", RuneSymbol::String("Alice".to_string()));
// Set up English translations
let mut en_translations = HashMap::new();
en_translations.insert("welcome".to_string(), "Welcome {{name}}!".to_string());
engine.set_translations("en", en_translations);
// Set up French translations
let mut fr_translations = HashMap::new();
fr_translations.insert("welcome".to_string(), "Bienvenue {{name}}!".to_string());
engine.set_translations("fr", fr_translations);
// Use English
engine.set_locale("en");
let welcome_en = engine.render_string("{{t \"welcome\"}}", &context).unwrap();
// Output: "Welcome Alice!"
// Switch to French
engine.set_locale("fr");
let welcome_fr = engine.render_string("{{t \"welcome\"}}", &context).unwrap();
// Output: "Bienvenue Alice!"
Custom Filters Example (v0.3.0)
use mystical_runic::{RuneEngine, RuneScroll, RuneSymbol};
let mut engine = RuneEngine::new("./templates");
let mut context = RuneScroll::new();
context.set("text", RuneSymbol::String("hello world".to_string()));
// Register custom filters
engine.register_filter("reverse", |input: &str, _args: &[&str]| {
Ok(input.chars().rev().collect())
});
engine.register_filter("repeat", |input: &str, args: &[&str]| {
let times = args.get(0).map_or("1", |v| v).parse::<usize>().unwrap_or(1);
Ok(input.repeat(times))
});
let result = engine.render_string("{{text|reverse|upper|repeat:2}}", &context).unwrap();
// Output: "DLROW OLLEHDLROW OLLEH"
Math Filters Example (v0.3.0)
use mystical_runic::{RuneEngine, RuneScroll, RuneSymbol};
let mut engine = RuneEngine::new("./templates");
let mut context = RuneScroll::new();
context.set("price", RuneSymbol::Number(100));
context.set("tax_rate", RuneSymbol::Number(8));
// Complex calculations with chaining
let template = "Price: ${{price}}, Total: {{price|multiply:tax_rate|divide:100|add:price|round:2}}";
let result = engine.render_string(template, &context).unwrap();
// Output: "Price: $100, Total: 108.00"
Pluralization Example (v0.3.0)
use mystical_runic::{RuneEngine, RuneScroll, RuneSymbol};
let mut engine = RuneEngine::new("./templates");
let mut context = RuneScroll::new();
let template = "You have {{count}} {{plural count \"apple\" \"apples\"}}";
context.set("count", RuneSymbol::Number(1));
let result = engine.render_string(template, &context).unwrap();
// Output: "You have 1 apple"
context.set("count", RuneSymbol::Number(5));
let result = engine.render_string(template, &context).unwrap();
// Output: "You have 5 apples"
๐ฎ Examples
Check out the examples/ directory for magical demonstrations:
real_world_demo/- โญ COMPLETE DEMO APPLICATION - Full-featured e-commerce/blog showcasing ALL v0.3.4 features- ๐ฎ Run with:
cd examples/real_world_demo && ./run_demo.sh - ๐ Generates complete HTML website (10KB+)
- ๐ NEW: Nested loops, recursive includes, path traversal protection
- ๐ Multi-language (FR/EN), math filters, custom filters, macros, inheritance
- ๐ฎ Run with:
spell_casting.rs- Fantasy RPG character sheet generator- More examples coming with each release!
๐ฆ Rust Compatibility
Minimum Supported Rust Version (MSRV): 1.74.0+
Edition: Rust 2021 (with future Rust 2024 readiness)
Tested on: Rust 1.74.0 through latest stable
Future-Proof Design
- Modern Rust patterns and idioms
- Prepared for Rust 2024 edition migration
- Zero unsafe code
- Comprehensive test coverage (173+ tests)
- Zero compilation warnings
Development Setup
git clone https://github.com/yrbane/mystical-runic.git
cd mystical-runic
cargo build
cargo test
๐งช Test-Driven Development (TDD) Methodology
Mystical-Runic follows strict Test-Driven Development practices. When contributing, please observe the sacred TDD ritual:
๐ด Red โ ๐ข Green โ ๐ต Refactor Cycle
-
๐ด RED - Write a Failing Test First
# Write your test before any implementation cargo test your_new_feature_test # โ Should fail - good! -
๐ข GREEN - Write Minimal Code to Pass
# Write just enough code to make the test pass cargo test your_new_feature_test # โ Should pass - excellent! -
๐ต REFACTOR - Improve Without Breaking
# Clean up code while keeping tests green cargo test # All tests should still pass
"Tests are the safety net that lets you refactor fearlessly." โ TDD Proverb
๐ Changelog
v0.4.1 (Latest Release) - The IDE Integration Edition
- ๐ป NEW: Language Server Protocol Support: Complete LSP implementation for template editing with
parse_for_lsp() - ๐จ NEW: Syntax Highlighting: Semantic token analysis with
tokenize_for_syntax_highlighting()for editor integration - ๐ก NEW: Auto-completion: Intelligent completion for variables, filters, and directives with
get_completions_at_position() - ๐จ NEW: Real-time Diagnostics: Error squiggles and warnings with
get_diagnostics_for_editor()for live error detection - โน๏ธ NEW: Hover Information: Variable type and value inspection with
get_hover_info_at_position() - ๐ NEW: Go to Definition: Navigate to macro definitions with
get_definition_at_position() - ๐งน Code Quality: Zero compiler warnings, clean production-ready codebase
- ๐งช 198+ Tests: Comprehensive test suite including all v0.4.1 IDE integration features
- ๐ Production Ready: All tests passing, full IDE support for enhanced developer experience
v0.4.0 - The Developer Experience Edition
- ๐ NEW: Enhanced Error Messages: Precise line/column error reporting with helpful context and suggestions
- ๐ NEW: Template Debugging: Complete debugging system with variable tracking and execution step analysis
- ๐ฅ NEW: Hot Reload: Automatic template reloading during development for faster iteration cycles
- ๐ NEW: Performance Metrics: Built-in performance tracking with execution time analysis
- ๐ฏ NEW: Intelligent Suggestions: Smart suggestions for template and variable name typos
- ๐งช 198+ Tests: Comprehensive test suite including all v0.4.0 developer experience features and v0.4.1 IDE integration
- ๐ Production Ready: All tests passing, enhanced developer productivity tools
v0.3.4 - The Advanced Features Edition
- ๐ NEW: Nested Loops: Complete support for nested loops with stack-based parsing (
{{for category in shops}}{{for item in category.items}}) - ๐ NEW: Recursive Includes: Unlimited depth recursive template includes (templates including templates)
- ๐ก๏ธ NEW: Path Traversal Protection: Enterprise-grade security preventing
../../../etc/passwdandC:\Windows\System32attacks - ๐ฎ Complete Real-World Demo: Full-featured e-commerce/blog application showcasing ALL features (
examples/real_world_demo/) - ๐ Enhanced Documentation: Complete README overhaul with comprehensive examples and demo application
- ๐งช 173+ Tests: Expanded test suite including all v0.3.4 features with comprehensive security testing
- ๐ Production Ready: All tests passing, zero warnings, full feature demonstration
v0.3.3 - The Warning-Free Edition
- ๐งน Zero Warnings: Complete cleanup of all compiler warnings for production readiness
- ๐ง Code Quality: Enhanced code quality and maintainability improvements
- โ Stability: All existing functionality maintained with improved reliability
v0.3.2 - The Enhancement Edition
- ๐ Enhanced i18n: Improved internationalization with better variable interpolation
- ๐ Smart Pluralization: Advanced plural form handling with locale-aware rules
- ๐ข Math Filter Improvements: Enhanced mathematical operations with better precision
- ๐จ Custom Filter API: Improved API for registering custom filters
v0.3.1 - The Stability Edition
- ๐ง Bug Fixes: Critical fixes for edge cases in template processing
- โก Performance: Optimized parsing and rendering pipeline
- ๐งช Testing: Enhanced test coverage for reliability improvements
v0.3.0 - The Global Sorcery Edition
- ๐ Internationalization (i18n): Full multi-language support with
{{t "key"}}syntax - ๐ Smart Pluralization: Automatic plural forms with
{{plural count "item" "items"}} - ๐ข Advanced Math Filters: Mathematical operations (
add,multiply,divide,percentage,round) - ๐จ Custom Filter API: Register your own filters with
engine.register_filter() - ๐ญ Dual Naming System: Choose between conventional (
TemplateEngine) or mystical (RuneEngine) styles - ๐งช 150+ Tests: Comprehensive test suite covering all new features
v0.2.0 - The Advanced Sorcery Edition
- ๐ฐ Template Inheritance: Advanced layout system with nested inheritance support
- ๐ง Powerful Filters: Built-in filters (
upper,lower,currency,truncate,date) with chaining - ๐ฆ Reusable Macros: Define and invoke template components with parameters
- ๐ Enhanced Deep Navigation: Unlimited depth dot notation (
{{game.player.stats.level}}) - โก Performance Boost: Bytecode compilation, parallel processing, memory mapping
- ๐งช 127+ Tests: Comprehensive test coverage including v0.2.0 features
- ๐ง Bug Fixes: Fixed nested layout inheritance and function call error handling
- ๐ Zero Dependencies: Pure Rust implementation
v0.1.4 (Stability Release)
- ๐ง Fixed nested layout inheritance block replacement boundary calculation
- ๐ก๏ธ Enhanced loop error handling for unsupported function calls
- ๐ Maintained backward compatibility for missing variables in loops
- โ All 127 tests passing with comprehensive coverage
v0.1.1 (Security & Testing Release)
- ๐ก๏ธ Comprehensive security testing suite
- ๐งช 85+ tests with 100% coverage following TDD methodology
- ๐ Complete documentation with TDD development guidelines
- ๐ Advanced XSS and injection protection
- โก Performance optimizations and stress testing
- ๐ด๐ข๐ต Strict Test-Driven Development practices implemented
v0.1.0 (Initial Release)
- โจ Core template engine with Mustache-inspired syntax
- ๐ XSS-safe HTML escaping by default
- โก Template caching for performance
- ๐ฏ Support for variables, conditionals, loops, includes, and comments
- ๐งช Comprehensive test suite with high coverage
- ๐ Complete documentation and examples
๐บ๏ธ Roadmap
โ v0.3.0-v0.5.2 - COMPLETED Features
๐ง Filters & I18n (v0.3.0-v0.3.4)
- โ
i18n Support:
{{t "key"}}syntax for translations - โ Pluralization: Smart plural forms based on count
- โ Custom Filter Registration: API for user-defined filters
- โ Advanced Math Filters: Mathematical operations and formatting
๐๏ธ Core Engine (v0.3.4)
- โ Nested Loops: Stack-based parsing for complex nested structures
- โ Recursive Includes: Deep template inclusion hierarchies
- โ Path Traversal Protection: Enterprise-grade security features
- โ Complete Real-World Demo: Full-featured showcase application
๐ ๏ธ Developer Experience (v0.4.0-v0.4.1)
- โ Enhanced Error Messages: Line/column numbers and intelligent suggestions
- โ Template Debugging: Step-through debugging with variable tracking
- โ Hot Reload: Development-time template reloading
- โ Language Server Protocol: Complete LSP support for template editing
- โ Syntax Highlighting: Semantic token analysis for editor integration
- โ Auto-completion: Intelligent variable, filter, and directive completion
- โ Real-time Diagnostics: Error squiggles and warnings in editors
- โ Hover Information: Variable type and value inspection
- โ Go to Definition: Navigate to macro and template definitions
๐ Ecosystem Integration (v0.5.0-v0.5.2)
- โ Async Support: Non-blocking template rendering
- โ Web Framework Integration: First-class Axum, Warp, Actix support
- โ WASM Compatibility: Browser and edge runtime support
- โ CLI Tools: Command-line template processing utilities
- โ Performance Monitoring: Advanced metrics collection (v0.5.1)
- โ Enterprise Security: Threat classification and audit logging (v0.5.1)
๐ Why "Mystical-Runic"?
Because templating is basically ancient magic:
- You write mysterious symbols (
{{}}) that transform into reality - Variables appear and disappear like spirits
- One wrong bracket and your entire spell explodes
- Senior developers guard the template secrets like ancient druids
- Documentation is written in a language only the initiated understand
- And just like real magic, it works perfectly until production ๐ฅ
๐ Performance Benchmarks
Mystical-Runic v0.5.2 includes comprehensive performance benchmarks demonstrating enterprise-grade performance:
# Quick performance test
cargo build --release
rustc --edition 2021 benchmarks/simple_benchmark.rs -L target/release/deps --extern mystical_runic=target/release/libmystical_runic.rlib -O && ./simple_benchmark
๐ฏ Performance Results
- Template Rendering: ~2.7ยตs per simple template (excellent)
- Filter Processing: ~4.4ยตs per filter chain (optimized)
- Complex Templates: ~470ยตs per complex template (scalable)
- Large Data Sets: 215ms per 1000 items (production-ready)
๐ Available Benchmarks
simple_benchmark.rs- Core functionality performance โv0_5_2_performance_benchmark.rs- Comprehensive enterprise testing ๐งecosystem_benchmark.rs- Async and CLI integration testing ๐
See benchmarks/README.md for detailed benchmark documentation and results.
๐ Links
- ๐ API Documentation: docs.rs/mystical-runic
- ๐ซ๐ท User Guide: Documentation HTML (franรงais)
- ๐ฆ Crates.io: crates.io/crates/mystical-runic
- ๐ง Repository: github.com/yrbane/mystical-runic
- ๐ Issues: github.com/yrbane/mystical-runic/issues
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
"May your templates be bug-free and your variables always defined."
โ Ancient DevOps Proverb
๐ฎโจ Happy templating! โจ๐ฎ
Dependencies
~0โ15MB
~167K SLoC