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

Add 'Environment::render_named_str()' #149

Merged
merged 2 commits into from Nov 19, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 28 additions & 3 deletions minijinja/src/environment.rs
Expand Up @@ -206,11 +206,36 @@ impl<'source> Environment<'source> {
pub fn render_str<S: Serialize>(&self, source: &str, ctx: S) -> Result<String, Error> {
// reduce total amount of code faling under mono morphization into
// this function, and share the rest in _eval.
self._render_str(source, Value::from_serializable(&ctx))
self._render_str("<string>", source, Value::from_serializable(&ctx))
}

fn _render_str(&self, source: &str, root: Value) -> Result<String, Error> {
let name = "<string>";
/// Parses and renders a template from a string in one go with name.
///
/// Like [`render_str`](Self::render_str), but provide a name for the
/// template to be used instead of the default `<string>`.
///
/// ```
/// # use minijinja::{Environment, context};
/// let env = Environment::new();
/// let rv = env.render_named_str(
/// "template_name",
/// "Hello {{ name }}",
/// context! { name => "World" }
/// );
/// println!("{}", rv.unwrap());
/// ```
pub fn render_named_str<S: Serialize>(
&self,
name: &str,
source: &str,
ctx: S,
) -> Result<String, Error> {
// reduce total amount of code faling under mono morphization into
// this function, and share the rest in _eval.
self._render_str(name, source, Value::from_serializable(&ctx))
}

fn _render_str(&self, name: &str, source: &str, root: Value) -> Result<String, Error> {
let compiled = ok!(CompiledTemplate::from_name_and_source(name, source));
let mut rv = String::new();
Vm::new(self)
Expand Down