kaj / ructe

Rust Compiled Templates with static-file handling
https://crates.io/crates/ructe
453 stars 33 forks source link

directly output string instead of a function #117

Open prabirshrestha opened 2 years ago

prabirshrestha commented 2 years ago

Is it possible to add a feature such that templates to return string instead of function if the feature flag is enabled This makes it easy to onboard to new frameworks. More info at https://github.com/salvo-rs/salvo/issues/147#issuecomment-1242800547.

// current
let mut buf = Vec::new();
templates::hello(&mut buf, "world");
response.render(buf);

// new
response.render(templates::hello_world_str("world"));

//cc @chrislearn

kaj commented 1 year ago

It is possible to define a function render like this:

fn rendertemplate<F>(f: F) -> String {
  let mut buf = Vec::new();
  f(&mut buf).unwrap(); // Or return a Result<String>
  buf
}

That can be used as:

rendertemplate(|out| templates::hello_html(out, "world"));

If the function is made a method of an extension trait for your response type, it could be called as:

response.rendertemplate(|out| templates::hello_html(out, "world"));

This is done in the warp03 feature. I'm not familiar with the salvo crate, but it seems that it is using hyper, so maybe warp should have a feature providing that extension crate for http::Response ? But in that case, it would seem more natural for me to provide it for hyper::response::Builder, but it seems that salvo uses a &mut Response rather than letting the handler use a builder. Maybe the extension trait can be provided both for http::request::Builder and http::Request.