mystical-runic

Crates.iomystical-runic
lib.rsmystical-runic
version0.5.3
created_at2025-08-17 08:51:43.226047+00
updated_at2025-08-20 01:14:56.962213+00
descriptionHigh-performance templating engine for Rust with enterprise security, advanced monitoring, comprehensive developer tools, and ecosystem integration. Zero-dependency core with optional async, web framework, WASM, and CLI features.
homepagehttps://github.com/yrbane/mystical-runic
repositoryhttps://github.com/yrbane/mystical-runic.git
max_upload_size
id1799248
size532,079
(yrbane)

documentation

https://docs.rs/mystical-runic

README

๐Ÿ”ฎ Mystical-Runic - High-Performance Template Engine

Zero-dependency, high-performance templating engine for Rust with enterprise-grade features

Crates.io Documentation License: MIT Build Status

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, truncate with 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/passwd and C:\Windows\System32 attacks
  • 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
  • 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 processing
    • process_files() - File-based template rendering
    • batch_process() - Multiple template processing
    • TemplateWatcher - 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/passwd attacks
  • ๐Ÿ—๏ธ 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: &lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;

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
  • 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

  1. ๐Ÿ”ด RED - Write a Failing Test First

    # Write your test before any implementation
    cargo test your_new_feature_test
    # โŒ Should fail - good!
    
  2. ๐ŸŸข GREEN - Write Minimal Code to Pass

    # Write just enough code to make the test pass
    cargo test your_new_feature_test
    # โœ… Should pass - excellent!
    
  3. ๐Ÿ”ต 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/passwd and C:\Windows\System32 attacks
  • ๐ŸŽฎ 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

๐Ÿ“„ 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! โœจ๐Ÿ”ฎ

Commit count: 0

cargo fmt