Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

directly output string instead of a function #117

Open
prabirshrestha opened this issue Sep 10, 2022 · 1 comment
Open

directly output string instead of a function #117

prabirshrestha opened this issue Sep 10, 2022 · 1 comment

Comments

@prabirshrestha
Copy link
Contributor

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 salvo-rs/salvo#147 (comment).

// 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
Copy link
Owner

kaj commented Jan 21, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants