Rusty Handlebars Parser
A type-safe Handlebars template parser and compiler for Rust. This crate provides the core parsing and compilation functionality for the rusty-handlebars templating engine.
Features
- Type-safe template parsing and compilation
- HTML escaping and safety
- Optional HTML minification
- Block helper support
- Expression evaluation
- Variable resolution and scope management
- Compile-time template validation
Components
Expression Parser
The expression parser handles various types of Handlebars expressions:
- Variables:
{{name}} - HTML-escaped variables:
{{{name}}} - Block helpers:
{{#helper}}...{{/helper}} - Comments:
{{! comment }} - Escaped content:
\{{name}}
Block Helpers
Built-in block helpers include:
if/unlessfor conditional renderingif_some/if_some_reffor Option handlingwith/with_reffor context changeseach/each_reffor collection iteration
Compiler
The compiler transforms Handlebars templates into Rust code:
- Resolves variables and scopes
- Compiles block helpers
- Handles HTML escaping
- Generates type-safe code
Usage
Basic Template Compilation
use ;
use add_builtins;
let mut block_map = new;
add_builtins;
let options = Options ;
let compiler = new;
let rust = compiler.compile?;
Complex Template Example
let template = r#"
<div class="user-profile">
{{#if user}}
<h1>{{user.name}}</h1>
{{#if user.bio}}
<p class="bio">{{user.bio}}</p>
{{else}}
<p class="no-bio">No bio available</p>
{{/if}}
{{#if_some user.posts as post}}
<div class="posts">
<h2>Posts</h2>
{{#each post as post}}
<article class="post">
<h3>{{post.title}}</h3>
<p>{{post.content}}</p>
<div class="meta">
<span>Posted on {{post.date}}</span>
{{#if post.tags}}
<div class="tags">
{{#each post.tags as tag}}
<span class="tag">{{tag}}</span>
{{/each}}
</div>
{{/if}}
</div>
</article>
{{/each}}
</div>
{{/if_some}}
{{else}}
<p>Please log in to view your profile</p>
{{/if}}
</div>
"#;
let rust = compiler.compile?;
HTML Minification
When the minify-html feature is enabled, the parser can optimize HTML output:
use COMPRESS_CONFIG;
The minification configuration:
- Preserves Handlebars template syntax
- Maintains HTML validity
- Optimizes JavaScript and CSS
- Keeps essential HTML structure
Error Handling
The parser provides detailed error information:
use ;
Module Structure
compiler.rs: Core compilation logicblock.rs: Block helper implementationsexpression.rs: Expression parsingexpression_tokenizer.rs: Tokenization of expressionserror.rs: Error handlingbuild_helper.rs: Build-time configuration
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.