Handlebars loop (each) on array
examples/handlebars/handlebars-loop/template.html
<h1>Fruits</h1> <ul> {{#each fruits as |fruit|}} <li>{{fruit}}</li> {{/each}} </ul>
examples/handlebars/handlebars-loop/hello.html
<h1>Fruits</h1> <ul> <li>apple</li> <li>banana</li> <li>peach</li> </ul>
examples/handlebars/handlebars-loop/src/main.rs
use handlebars::Handlebars; use serde_json::json; use std::error::Error; use std::fs::File; use std::io::Read; use std::io::Write; fn main() { let filename = "hello.html"; let template = "template.html"; match render_without_register(template, filename) { Ok(_) => println!(), Err(_) => println!("error"), } } fn render_without_register(template_file: &str, filename: &str) -> Result<(), Box<dyn Error>> { let mut template = String::new(); match File::open(template_file) { Ok(mut file) => { file.read_to_string(&mut template).unwrap(); } Err(error) => { println!("Error opening file {}: {}", template_file, error); } } let reg = Handlebars::new(); let fruits = ["apple", "banana", "peach"]; let html = reg.render_template(&template, &json!({"fruits": fruits}))?; let mut file = File::create(filename).unwrap(); writeln!(&mut file, "{}", html).unwrap(); Ok(()) }
examples/handlebars/handlebars-loop/Cargo.toml
[package] name = "handlebars-quick" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] handlebars = "4.3.7" serde_json = "1.0.97"