### truncate example with all attributes Source: https://docs.rs/minijinja-contrib/latest/minijinja_contrib/filters/fn.truncate.html Example using all keyword arguments: length=5, killwords=true, end='...', and leeway=2. ```jinja {{ "Hello World"|truncate( length=5, killwords=true, end='...', leeway=2 ) }} ``` -------------------------------- ### Basic Example Source: https://docs.rs/minijinja/latest/minijinja/functions/trait.Function.html Example of adding a simple function that reads a file. ```APIDOC ## Basic Example ### Description Shows how to define and add a function that reads a file and returns its contents. ### Code ```rust use minijinja::{Error, ErrorKind}; fn include_file(name: String) -> Result { std::fs::read_to_string(&name) .map_err(|e| Error::new( ErrorKind::InvalidOperation, "cannot load file" ).with_source(e)) } env.add_function("include_file", include_file); ``` ### Template Usage ``` {{ include_file("filename.txt") }} ``` ``` -------------------------------- ### Example using args! macro Source: https://docs.rs/minijinja/latest/minijinja/macro.args.html Example of using `args!` to create arguments for a `call` method, including both positional and keyword arguments. ```rust value.call(state, args!(1, 2, foo => "bar")); ``` -------------------------------- ### get() example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Returns a reference to an element or subslice depending on the type of index. If given a position, returns the element at that position or None if out of bounds. If given a range, returns the subslice or None if out of bounds. The example shows that get(1) returns the element at index 1, get(0..2) returns the subslice [10, 40], and out-of-bounds indices return None. ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### Vec::reserve_exact example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Example of reserving the minimum capacity for at least additional elements. ```rust let mut vec = vec![1]; vec.reserve_exact(10); assert!(vec.capacity() >= 11); ``` -------------------------------- ### Variadic Example Source: https://docs.rs/minijinja/latest/minijinja/functions/trait.Function.html Example of a variadic function that sums its arguments. ```APIDOC ## Variadic Example ### Description Shows how to define a variadic function using `Rest` to capture remaining arguments. ### Code ```rust use minijinja::value::Rest; fn sum(values: Rest) -> i64 { values.iter().sum() } env.add_function("sum", sum); ``` ### Template Usage ``` {{ sum(1, 2, 3) }} -> 6 ``` ``` -------------------------------- ### format example Source: https://docs.rs/minijinja/latest/minijinja/struct.State.html Formats a value to a string using the environment's formatter. The example formats the integer 42 and asserts the result is "42". ```rust let rv = state.format(Value::from(42)).unwrap(); assert_eq!(rv, "42"); ``` -------------------------------- ### from_serialize documentation with example Source: https://docs.rs/minijinja/latest/src/minijinja/value/mod.rs.html Documentation for the from_serialize method, including a code example showing how to create a Value from a serializable vector. The method may return invalid values if serialization fails. ```rust /// Creates a value from something that can be serialized. /// /// This is the method that MiniJinja will generally use whenever a serializable /// object is passed to one of the APIs that internally want to create a value. /// For instance this is what [`context!`](crate::context) and /// [`render`](crate::Template::render) will use. /// /// During serialization of the value, [`serializing_for_value`] will return /// `true` which makes it possible to customize serialization for MiniJinja. /// For more information see [`serializing_for_value`]. /// /// ``` /// # use minijinja::value::Value; /// let val = Value::from_serialize(&vec![1, 2, 3]); /// ``` /// /// This method does not fail but it might return a value that is not valid. Such /// values will when operated on fail in the template engine in most situations. /// This for instance can happen if the underlying implementation of [`Serialize`] /// fails. There are also cases where invalid objects are silently hidden in the /// engine today. This is for instance the case for when keys are used in hash maps ``` -------------------------------- ### partition_point range example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Shows how to find the whole range of matching items using partition_point instead of an arbitrary match. The example also demonstrates inserting an item into a sorted vector while maintaining sort order. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let low = s.partition_point(|x| x < &1); assert_eq!(low, 1); let high = s.partition_point(|x| x <= &1); assert_eq!(high, 5); let r = s.binary_search(&1); assert!((low..high).contains(&r.unwrap())); assert!(s[..low].iter().all(|&x| x < 1)); assert!(s[low..high].iter().all(|&x| x == 1)); assert!(s[high..].iter().all(|&x| x > 1)); // For something not found, the "range" of equal items is empty assert_eq!(s.partition_point(|x| x < &11), 9); assert_eq!(s.partition_point(|x| x <= &11), 9); assert_eq!(s.binary_search(&11), Err(9)); ``` -------------------------------- ### AutoReloader template loading example Source: https://docs.rs/minijinja-autoreload/latest/src/minijinja_autoreload/lib.rs.html This example demonstrates how to use the AutoReloader with the MiniJinja source feature to automatically load templates from the file system. ```rust # fn test() -> Result<(), minijinja::Error> { use minijinja_autoreload::AutoReloader; use minijinja::{Environment, path_loader}; let reloader = AutoReloader::new(|notifier| { let template_path = "path/to/templates"; let mut env = Environment::new(); env.set_loader(path_loader(template_path)); notifier.watch_path(template_path, true); Ok(env) }); let env = reloader.acquire_env()?; let tmpl = env.get_template("index.html")?; # Ok(()) } fn main() { test().unwrap_err(); } ``` -------------------------------- ### as_simd example with portable_simd Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Example for `as_simd` using the nightly-only `portable_simd` feature. It shows splitting a slice into prefix, middle, and suffix SIMD parts, and a `basic_simd_sum` function that sums a slice using `f32x4`. ```rust #![feature(portable_simd)] use core::simd::prelude::*; let short = &[1, 2, 3]; let (prefix, middle, suffix) = short.as_simd::<4>(); assert_eq!(middle, []); // Not enough elements for anything in the middle // They might be split in any possible way between prefix and suffix let it = prefix.iter().chain(suffix).copied(); assert_eq!(it.collect::>(), vec![1, 2, 3]); fn basic_simd_sum(x: &[f32]) -> f32 { use std::ops::Add; let (prefix, middle, suffix) = x.as_simd(); let sums = f32x4::from_array([ prefix.iter().copied().sum(), 0.0, 0.0, suffix.iter().copied().sum(), ]); let sums = middle.iter().copied().fold(sums, f32x4::add); sums.reduce_sum() } let numbers: Vec = (1..101).map(|x| x as _).collect(); assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0); ``` -------------------------------- ### get_temp example Source: https://docs.rs/minijinja/latest/minijinja/struct.State.html Shows how to use temps to store and modify state during rendering. The example defines an 'inc' function that increments a counter stored as a temp. ```rust use minijinja::{Value, State}; fn inc(state: &State) -> Value { let old = state .get_temp("my_counter") .unwrap_or_else(|| Value::from(0i64)); let new = Value::from(i64::try_from(old).unwrap() + 1); state.set_temp("my_counter", new.clone()); new } ``` -------------------------------- ### Create environment with path_loader Source: https://docs.rs/minijinja/latest/minijinja/fn.path_loader.html Example usage of path_loader to set a template loader on an Environment. Templates starting with a dot or in a dot-folder cannot be loaded. ```rust fn create_env() -> Environment<'static> { let mut env = Environment::new(); env.set_loader(path_loader("path/to/templates")); env } ``` -------------------------------- ### Optional Arguments Example Source: https://docs.rs/minijinja/latest/minijinja/functions/trait.Function.html Example of a function with optional arguments using Option. ```APIDOC ## Optional Arguments Example ### Description Shows how to define a function with optional arguments using `Option`. ### Code ```rust fn substr(value: String, start: u32, end: Option) -> String { let end = end.unwrap_or(value.len() as _); value.get(start as usize..end as usize).unwrap_or_default().into() } env.add_filter("substr", substr); ``` ### Template Usage ``` {{ "Foo Bar Baz"|substr(4) }} -> Bar Baz {{ "Foo Bar Baz"|substr(4, 7) }} -> Bar ``` ``` -------------------------------- ### binary_search_by_key example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Shows how to use `binary_search_by_key` on a slice of pairs sorted by their second elements. The example asserts the returned index for found values, the insertion index for missing values, and that a match can fall within a range when multiple matches exist. ```rust let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13), (1, 21), (2, 34), (4, 55)]; assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9)); assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7)); assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13)); let r = s.binary_search_by_key(&1, |&(a, b)| b); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### Usage example: {{ 42 is even }} -> true Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_even.html Example usage in a template. The expression `{{ 42 is even }}` evaluates to `true`. ```text {{ 42 is even }} -> true ``` -------------------------------- ### resize_with example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Resizes the vector in-place, filling new slots with values from the closure. The first example uses Default::default to fill with zeros; the second uses a closure that doubles a counter. Panics if the new capacity exceeds isize::MAX bytes. ```rust let mut vec = vec![1, 2, 3]; vec.resize_with(5, Default::default); assert_eq!(vec, [1, 2, 3, 0, 0]); let mut vec = vec![]; let mut p = 1; vec.resize_with(4, || { p *= 2; p }); assert_eq!(vec, [2, 4, 8, 16]); ``` -------------------------------- ### Vec::capacity example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Example of checking the capacity of a vector. ```rust let mut vec: Vec = Vec::with_capacity(10); vec.push(42); assert!(vec.capacity() >= 10); ``` -------------------------------- ### get_or_set_temp_object example Source: https://docs.rs/minijinja/latest/minijinja/struct.State.html Shows how to register an object as a temp, creating it if not present. The example defines an 'inc' function that uses an atomic counter object. ```rust use std::sync::atomic::{AtomicUsize, Ordering}; use minijinja::{Value, State}; use minijinja::value::Object; #[derive(Debug, Default)] struct MyObject(AtomicUsize); impl Object for MyObject {} fn inc(state: &State) -> Value { let obj = state.get_or_set_temp_object("my_counter", MyObject::default); let old = obj.0.fetch_add(1, Ordering::AcqRel); Value::from(old + 1) } ``` -------------------------------- ### from_function example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Value.html Creates a callable value from a function. The example wraps a closure that squares a u32 input. ```rust let pow = Value::from_function(|a: u32| a * a); ``` -------------------------------- ### trim_prefix slice method example (nightly) Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Demonstrates the nightly-only `trim_prefix` method on slices. The example shows that when the prefix is present, the subslice after it is returned; when absent, the original slice is returned. Requires the `trim_prefix_suffix` feature gate. ```rust #![feature(trim_prefix_suffix)] let v = &[10, 40, 30]; // Prefix present - removes it assert_eq!(v.trim_prefix(&[10]), &[40, 30][..]); assert_eq!(v.trim_prefix(&[10, 40]), &[30][..]); assert_eq!(v.trim_prefix(&[10, 40, 30]), &[][..]); // Prefix absent - returns original slice assert_eq!(v.trim_prefix(&[50]), &[10, 40, 30][..]); assert_eq!(v.trim_prefix(&[10, 50]), &[10, 40, 30][..]); let prefix : &str = "he"; assert_eq!(b"hello".trim_prefix(prefix.as_bytes()), b"llo".as_ref()); ``` -------------------------------- ### Vec::push example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Example of appending an element to a vector using push. ```rust let mut vec = vec![1, 2]; vec.push(3); assert_eq!(vec, [1, 2, 3]); ``` -------------------------------- ### Vec::reserve example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Example of reserving capacity for at least additional elements. ```rust let mut vec = vec![1]; vec.reserve(10); assert!(vec.capacity() >= 11); ``` -------------------------------- ### try_shrink_to_fit example: fallible shrink (nightly) Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Shows how to use the nightly-only Vec::try_shrink_to_fit to attempt to shrink capacity, returning a Result. The example uses expect to handle the error. ```rust #![feature(vec_fallible_shrink)] let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3]); assert!(vec.capacity() >= 10); vec.try_shrink_to_fit().expect("why is the test harness failing to shrink to 12 bytes"); assert!(vec.capacity() >= 3); ``` -------------------------------- ### truncate filter usage example Source: https://docs.rs/minijinja-contrib/latest/minijinja_contrib/filters/fn.truncate.html Template example showing the truncate filter with length=5 on the string "Hello World". ```jinja {{ "Hello World"|truncate(length=5) }} ``` -------------------------------- ### binary_search_by example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Demonstrates binary_search_by with a comparator function. The comparator uses probe.cmp(&seek) to compare each element to the target. The example shows found and not-found cases, including the range of possible matches for a duplicate value. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let seek = 13; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9)); let seek = 4; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7)); let seek = 100; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13)); let seek = 1; let r = s.binary_search_by(|probe| probe.cmp(&seek)); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### Vec::capacity with zero-sized elements example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Example showing that a vector of zero-sized elements always has capacity usize::MAX. ```rust #[derive(Clone)] struct ZeroSized; fn main() { assert_eq!(std::mem::size_of::(), 0); let v = vec![ZeroSized; 0]; assert_eq!(v.capacity(), usize::MAX); } ``` -------------------------------- ### Template examples for is_iterable Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_iterable.html Two template examples showing that `[1, 2, 3]` is iterable (true) and `42` is not (false). ```jinja {{ [1, 2, 3] is iterable }} -> true {{ 42 is iterable }} -> false ``` -------------------------------- ### Usage example in Jinja template Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_false.html Example of using `is_false` in a Jinja template to check if a value is `false`. ```jinja {% if value is false %}...{% endif %} ``` -------------------------------- ### trim_suffix slice method example (nightly) Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Demonstrates the nightly-only `trim_suffix` method on slices. The example shows that when the suffix is present, the subslice before it is returned; when absent, the original slice is returned. Requires the `trim_prefix_suffix` feature gate. ```rust #![feature(trim_prefix_suffix)] let v = &[10, 40, 30]; // Suffix present - removes it assert_eq!(v.trim_suffix(&[30]), &[10, 40][..]); assert_eq!(v.trim_suffix(&[40, 30]), &[10][..]); assert_eq!(v.trim_suffix(&[10, 40, 30]), &[][..]); // Suffix absent - returns original slice assert_eq!(v.trim_suffix(&[50]), &[10, 40, 30][..]); assert_eq!(v.trim_suffix(&[50, 30]), &[10, 40, 30][..]); ``` -------------------------------- ### shrink_to_fit example: shrink capacity to fit length Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Shows how to use Vec::shrink_to_fit to reduce capacity to the minimum needed for the current length. The example asserts that capacity is at least 3 after shrinking. ```rust let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3]); assert!(vec.capacity() >= 10); vec.shrink_to_fit(); assert!(vec.capacity() >= 3); ``` -------------------------------- ### first() example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Returns the first element of the slice, or None if it is empty. The example asserts that the first element of [10, 40, 30] is 10 and that an empty slice returns None. ```rust let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); ``` -------------------------------- ### shrink_to example: shrink capacity with lower bound Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Shows how to use Vec::shrink_to to reduce capacity to a specified lower bound. The example demonstrates that capacity remains at least the given value and at least the length. ```rust let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3]); assert!(vec.capacity() >= 10); vec.shrink_to(4); assert!(vec.capacity() >= 4); vec.shrink_to(0); assert!(vec.capacity() >= 3); ``` -------------------------------- ### strip_prefix slice method example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Demonstrates the `strip_prefix` method on slices. The example shows that when the prefix is present, the subslice after it is returned wrapped in `Some`; when absent, `None` is returned. It also covers empty prefix and prefix equal to the whole slice cases. ```rust let v = &[10, 40, 30]; assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..])); assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..])); assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..])); assert_eq!(v.strip_prefix(&[50]), None); assert_eq!(v.strip_prefix(&[10, 50]), None); let prefix : &str = "he"; assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); ``` -------------------------------- ### Vec::push_mut example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Example of appending an element and getting a mutable reference to it using push_mut. ```rust let mut vec = vec![1, 2]; let last = vec.push_mut(3); assert_eq!(*last, 3); assert_eq!(vec, [1, 2, 3]); let last = vec.push_mut(3); *last += 1; assert_eq!(vec, [1, 2, 3, 4]); ``` -------------------------------- ### min template usage example Source: https://docs.rs/minijinja/latest/minijinja/filters/fn.min.html Example of using the `min` filter in a template to get the smallest item from a list. ```jinja {{ [1, 2, 3, 4]|min }} -> 1 ``` -------------------------------- ### Render a template with environment and context in Rust Source: https://docs.rs/minijinja/latest/minijinja This example shows how to create an Azure OpenAI-compatible client using the `azure_openai` SDK. ```rust use minijinja::{Environment, context}; let mut env = Environment::new(); env.add_template("hello", "Hello {{ name }}!").unwrap(); let tmpl = env.get_template("hello").unwrap(); println!("{}", tmpl.render(context!(name => "John")).unwrap()); ``` ```output Hello John! ``` -------------------------------- ### Start unaryop! for unary-only operators Source: https://docs.rs/minijinja/latest/src/minijinja/compiler/parser.rs.html Starts the definition of unary operator parsing for unary-only operators using the unaryop! macro. The snippet is incomplete as the source ends mid-definition. ```rust unaryop!(parse_unary_only, parse_primary, { ``` -------------------------------- ### is_startingwith template usage Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_startingwith.html Example usage of the is_startingwith test in a template. The first expression returns true because "foobar" starts with "foo", the second returns false because it does not start with "bar". ```jinja {{ "foobar" is startingwith "foo" }} -> true {{ "foobar" is startingwith "bar" }} -> false ``` -------------------------------- ### Value::downcast_object_ref() - Get reference to boxed object Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Value.html Returns a reference to the boxed object if it is of type T, or None otherwise. This is the reverse of from_object and from_dyn_object. The example defines a Thing struct implementing Object, creates a Value from it, and downcasts to get the id. ```rust use std::fmt; #[derive(Debug)] struct Thing { id: usize, } impl Object for Thing {} let x_value = Value::from_object(Thing { id: 42 }); let thing = x_value.downcast_object_ref::().unwrap(); assert_eq!(thing.id, 42); ``` -------------------------------- ### is_sorted example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Example for `is_sorted` showing that it returns `true` for sorted slices, `false` for unsorted ones, and `true` for empty or single-element slices. It also demonstrates that `f32::NAN` causes `false` because NaN is not comparable. ```rust let empty: [i32; 0] = []; assert!([1, 2, 2, 9].is_sorted()); assert!(![1, 3, 2, 4].is_sorted()); assert!([0].is_sorted()); assert!(empty.is_sorted()); assert!(![0.0, 1.0, f32::NAN].is_sorted()); ``` -------------------------------- ### Use subslice_range with split to get subslice ranges Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Shows how to use `subslice_range` with `split` to get the ranges of subslices. The example creates a slice of integers, splits it on zeros, and maps each subslice to its range using `subslice_range`. The assertions verify the expected ranges. ```rust use core::range::Range; let nums = &[0, 5, 10, 0, 0, 5]; let mut iter = nums .split(|t| *t == 0) .map(|n| nums.subslice_range(n).unwrap()); assert_eq!(iter.next(), Some(Range { start: 0, end: 0 })); assert_eq!(iter.next(), Some(Range { start: 1, end: 3 })); assert_eq!(iter.next(), Some(Range { start: 4, end: 4 })); assert_eq!(iter.next(), Some(Range { start: 5, end: 6 })); ``` -------------------------------- ### strip_circumfix slice method example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Demonstrates the `strip_circumfix` method on slices. The example shows that when the slice starts with the prefix and ends with the suffix without overlap, the middle subslice is returned wrapped in `Some`; otherwise `None` is returned. It also covers empty prefix/suffix and overlapping cases. ```rust let v = &[10, 50, 40, 30]; assert_eq!(v.strip_circumfix(&[10], &[30]), Some(&[50, 40][..])); assert_eq!(v.strip_circumfix(&[10], &[40, 30]), Some(&[50][..])); assert_eq!(v.strip_circumfix(&[10, 50], &[40, 30]), Some(&[][..])); assert_eq!(v.strip_circumfix(&[50], &[30]), None); assert_eq!(v.strip_circumfix(&[10], &[40]), None); assert_eq!(v.strip_circumfix(&[], &[40, 30]), Some(&[10, 50][..])); assert_eq!(v.strip_circumfix(&[10, 50], &[]), Some(&[40, 30][..])); assert_eq!(v.strip_circumfix(&[10, 50, 40], &[50, 40, 30]), None); ``` -------------------------------- ### Render a template with Environment and context! Source: https://docs.rs/minijinja Creates an Environment, adds a template named "hello", retrieves it, and renders it with a context containing name="John". The output is "Hello John!". Requires the minijinja crate and the context! macro. ```rust use minijinja::{Environment, context}; let mut env = Environment::new(); env.add_template("hello", "Hello {{ name }}!").unwrap(); let tmpl = env.get_template("hello").unwrap(); println!("{}", tmpl.render(context!(name => "John")).unwrap()); ``` ```text Hello John! ``` -------------------------------- ### Map filter invocation example Source: https://docs.rs/minijinja/latest/minijinja/filters/fn.map.html Template example showing how to apply the `lower` filter to each element of the `titles` sequence, then join the results. This demonstrates using `map` to invoke another filter by name. ```jinja Users on this page: {{ titles|map('lower')|join(', ') }} ``` -------------------------------- ### Value::len() - Get length of a value Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Value.html Returns the length of the contained value. Values without a length return None. The example creates a vector value and asserts its length is Some(4). ```rust let seq = Value::from(vec![1, 2, 3, 4]); assert_eq!(seq.len(), Some(4)); ``` -------------------------------- ### element_offset: None for unaligned element Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Shows that `element_offset` returns `None` when the element reference is not aligned to the start of an element. The example uses a flattened slice to create an unaligned reference that points between elements. ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### Using error range to get failing expression Source: https://docs.rs/minijinja/latest/minijinja/struct.Error.html Example showing how to use `template_source` and `range` to extract the failing expression from the template source. Requires the `debug` feature and debug mode enabled. ```rust let tmpl = env.template_from_str("Hello {{ foo + bar }}!").unwrap(); let err = tmpl.render(context!(foo => "a string", bar => 0)).unwrap_err(); let src = err.template_source().unwrap(); assert_eq!(&src[err.range().unwrap()], "foo + bar"); ``` -------------------------------- ### as_ptr_range: Get raw pointer range and check membership Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Use to get a half-open range of raw pointers spanning the slice, useful for foreign interfaces or checking pointer membership. The end pointer points one past the last element and requires extra caution. The example checks whether a pointer refers to an element of the slice. ```rust let a = [1, 2, 3]; let x = &a[1] as *const _; let y = &5 as *const _; assert!(a.as_ptr_range().contains(&x)); assert!(!a.as_ptr_range().contains(&y)); ``` -------------------------------- ### {% with %} multiple variables and unpacking Source: https://docs.rs/minijinja/latest/minijinja/syntax/index.html Multiple variables can be set at once and unpacking is supported. The example outputs 1, 2, 3. ```html {% with a = 1, (b, c) = [2, 3] %} {{ a }}, {{ b }}, {{ c }} (outputs 1, 2, 3) {% endwith %} ``` -------------------------------- ### rsplit: iterate subslices from the end Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Use to iterate over subslices separated by a predicate, starting from the end of the slice. The matched element is not included. The example shows splitting on the value 0, yielding subslices in reverse order. ```rust let slice = [11, 22, 33, 0, 44, 55]; let mut iter = slice.rsplit(|num| *num == 0); assert_eq!(iter.next().unwrap(), &[44, 55]); assert_eq!(iter.next().unwrap(), &[11, 22, 33]); assert_eq!(iter.next(), None); ``` -------------------------------- ### element_offset: get index of element reference Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Returns the index of an element reference within a slice. The element must point to the start of an element; otherwise returns `None`. This method uses pointer arithmetic and does not compare elements. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` -------------------------------- ### Environment::new Source: https://docs.rs/minijinja/latest/minijinja/struct.Environment.html Creates a new environment with sensible defaults, including all built-in filters, tests, and globals. ```APIDOC ## Environment::new ### Description Creates a new environment with sensible defaults. This environment does not yet contain any templates but it will have all the default filters, tests and globals loaded. If you do not want any default configuration you can use the alternative `empty` method. ### Method new ### Signature `pub fn new() -> Environment<'source>` ### Parameters None ### Returns - **Environment<'source>** - A new environment with default configuration. ### Example ```rust let mut env = Environment::new(); ``` ``` -------------------------------- ### Using Kwargs to modify values Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Kwargs.html This example shows how to use Kwargs in a function to modify a vector of values. It uses `get` to fetch optional parameters and `assert_all_used` to ensure all keyword arguments are consumed, returning an error otherwise. ```rust use minijinja::value::{Value, Kwargs}; use minijinja::Error; fn modify(mut values: Vec, options: Kwargs) -> Result, Error> { // get pulls a parameter of any type. Same as from_args. For optional // boolean values the type inference is particularly convenient. if let Some(true) = options.get("reverse")? { values.reverse(); } if let Some(limit) = options.get("limit")? { values.truncate(limit); } options.assert_all_used()?; Ok(values) } ``` -------------------------------- ### Handle VM instructions for stack, output, locals, and attributes Source: https://docs.rs/minijinja/latest/src/minijinja/vm/mod.rs.html Matches on `Instruction` variants to execute operations: `Swap` swaps top two stack values, `EmitRaw` writes a raw string, `Emit` formats and writes a value with escaping or custom formatter, `StoreLocal` stores a value in context, `Lookup` pushes a value from context, `GetAttr` gets an attribute with fast path, and `SetAttr` sets an attribute on a namespace. ```rust match instr { Instruction::Swap => { a = stack.pop(); b = stack.pop(); stack.push(a); stack.push(b); } Instruction::EmitRaw(val) => { // this only produces a format error, no need to attach // location information. ok!(out.write_str(val).map_err(Error::from)); } Instruction::Emit => { let value = stack.pop(); if self.env.is_default_formatter() { if strict_undefined && matches!(value.0, ValueRepr::Undefined(UndefinedType::Default)) { bail!(Error::from(ErrorKind::UndefinedError)); } ctx_ok!(write_escaped(out, state.auto_escape.get(), &value)); } else { ctx_ok!(self.env.format(&value, state, out)); } } Instruction::StoreLocal(name) => { state.ctx.store(name, stack.pop()); } Instruction::Lookup(name) => { stack.push(assert_valid!(state .lookup(name) .unwrap_or(Value::UNDEFINED))); } Instruction::GetAttr(name) => { a = stack.pop(); // This is a common enough operation that it's interesting to consider a fast // path here. This is slightly faster than the regular attr lookup because we // do not need to pass down the error object for the more common success case. // Only when we cannot look up something, we start to consider the undefined // special case. stack.push(match a.get_attr_fast(name) { Some(value) => assert_valid!(value), None => ctx_ok!(undefined_behavior.handle_undefined(a.is_undefined())), }); } Instruction::SetAttr(name) => { b = stack.pop(); a = stack.pop(); if let Some(ns) = b.downcast_object_ref::() { ns.set_value(name, a); } else { bail!(Error::new( ErrorKind::InvalidOperation, format!("can only assign to namespaces, not {}", b.kind()) )); } } } ``` -------------------------------- ### Get error byte range with Error::range() Source: https://docs.rs/minijinja/latest/src/minijinja/error.rs.html Use with the `debug` feature enabled and `Environment::set_debug(true)` to obtain the byte range of the error and index into the template source. The example renders a template with a type mismatch and asserts that the range covers the failing expression `foo + bar`. ```rust # use minijinja::{Error, Environment, context}; # let mut env = Environment::new(); # env.set_debug(true); let tmpl = env.template_from_str("Hello {{ foo + bar }}!").unwrap(); let err = tmpl.render(context!(foo => "a string", bar => 0)).unwrap_err(); let src = err.template_source().unwrap(); assert_eq!(&src[err.range().unwrap()], "foo + bar"); ``` -------------------------------- ### lines filter usage example Source: https://docs.rs/minijinja/latest/minijinja/filters/fn.lines.html An example of using the `lines` filter in a Minijinja template. The newline is removed in the process, and this example shows the expected output. ```jinja {{ "foo\nbar\nbaz"|lines }} -> ["foo", "bar", "baz"] ``` -------------------------------- ### build Source: https://docs.rs/minijinja/latest/minijinja/syntax/struct.SyntaxConfigBuilder.html Builds the final syntax config. ```APIDOC ## build ### Description Builds the final syntax config. ### Method build ### Signature pub fn build(&self) -> Result ### Parameters None ### Return Value - **Result** - The built SyntaxConfig or an error. ``` -------------------------------- ### AutoReloader with path_loader example Source: https://docs.rs/minijinja-autoreload/latest/index.html Shows how to create an AutoReloader that loads templates from a file system path using MiniJinja's source feature. The closure creates an environment with a path_loader and watches the template path for changes. The environment is acquired with acquire_env and a template is fetched. ```rust use minijinja_autoreload::AutoReloader; use minijinja::{Environment, path_loader}; let reloader = AutoReloader::new(|notifier| { let template_path = "path/to/templates"; let mut env = Environment::new(); env.set_loader(path_loader(template_path)); notifier.watch_path(template_path, true); Ok(env) }); let env = reloader.acquire_env()?; let tmpl = env.get_template("index.html")?; ``` -------------------------------- ### Basic Value Conversions with From Source: https://docs.rs/minijinja/latest/src/minijinja/value/mod.rs.html Shows how to create Value instances from Rust types using the From trait, including integers, unit, booleans, and maps. ```rust use std::collections::BTreeMap; # use minijinja::value::Value; let int_value = Value::from(42); let none_value = Value::from(()); let true_value = Value::from(true); let map = Value::from({ let mut m = BTreeMap::new(); m.insert("foo", 1); m.insert("bar", 2); m }); ``` -------------------------------- ### try_reserve_exact example: pre-reserve minimum memory Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Shows how to use Vec::try_reserve_exact to pre-allocate the minimum required memory, returning an error if allocation fails. Unlike try_reserve, it does not over-allocate. ```rust use std::collections::TryReserveError; fn process_data(data: &[u32]) -> Result, TryReserveError> { let mut output = Vec::new(); // Pre-reserve the memory, exiting if we can't output.try_reserve_exact(data.len())?; // Now we know this can't OOM in the middle of our complex work output.extend(data.iter().map(|&val| { val * 2 + 5 // very complicated })); Ok(output) } ``` -------------------------------- ### Apply filter with state.apply_filter Source: https://docs.rs/minijinja/latest/minijinja/struct.State.html This example demonstrates applying the "upper" filter to a string value and checking the result is "HELLO WORLD". ```rust let rv = state.apply_filter("upper", &["hello world".into()]).unwrap(); assert_eq!(rv.as_str(), Some("HELLO WORLD")); ``` -------------------------------- ### Add minijinja-embed as regular and build dependency Source: https://docs.rs/minijinja-embed/latest/minijinja_embed/index.html Use cargo add to add minijinja-embed as both a regular and build dependency. ```bash cargo add minijinja-embed cargo add minijinja-embed --build ``` -------------------------------- ### is_le Usage Examples Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_le.html Examples showing the usage of is_le as a test and within a select filter. ```jinja2 {{ 1 is le 2 }} -> true {{ [1, 2, 3]|select("<=", 2) }} => [1, 2] ``` -------------------------------- ### add_template example Source: https://docs.rs/minijinja/latest/minijinja/struct.Environment.html Loads a template from a string into the environment. The name parameter identifies the template, and the template can be retrieved later with get_template. This method fails if the template has a syntax error. ```rust let mut env = Environment::new(); env.add_template("index.html", "Hello {{ name }}!").unwrap(); ``` -------------------------------- ### is_mapping usage examples Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_mapping.html Template examples showing is_mapping returns true for a mapping and false for a list. ```jinja {{ {"foo": "bar"} is mapping }} -> true {{ [1, 2, 3] is mapping }} -> false ``` -------------------------------- ### Usage of str.format() style with format (Jinja template) Source: https://docs.rs/minijinja/latest/minijinja/filters/fn.format.html Shows the more convenient `str.format()` style, available via `minijinja-contrib`'s `pycompat` feature, producing `Hello, Alice!`. ```jinja {{ "{}, {name}!".format(greeting, name="Alice") }} -> Hello, Alice! ``` -------------------------------- ### Load default main bundle Source: https://docs.rs/minijinja-embed/latest/minijinja_embed/macro.load_templates.html Loads all templates from the default `main` bundle into the environment. Templates are eagerly loaded, so no loader is needed. ```rust minijinja_embed::load_templates!(&mut env); ``` -------------------------------- ### len() example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Returns the number of elements in the slice. The example asserts that the length of the array [1, 2, 3] is 3. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### {% include %} with template list and ignore missing Source: https://docs.rs/minijinja/latest/minijinja/syntax/index.html Provide a list of templates; the first existing one is included. With 'ignore missing', if none exist it renders nothing; otherwise it fails with an error. ```html {% include ['page_detailed.html', 'page.html'] %} {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %} ``` -------------------------------- ### Test is_float with Jinja examples Source: https://docs.rs/minijinja/latest/src/minijinja/tests.rs.html Checks if a value is a float. The examples show that 42 is not a float (false) and 42.0 is (true). ```jinja {{ 42 is float }} -> false {{ 42.0 is float }} -> true ``` -------------------------------- ### Splitting Rest into args and kwargs Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Kwargs.html This example shows how to split a `Rest` argument into positional arguments and keyword arguments using `from_args`. It is useful when working with functions that accept both types of arguments. ```rust fn my_func(args: Rest) -> Result { let (args, kwargs) = from_args::<(&[Value], Kwargs)>(&args)?; // do something with args and kwargs } ``` -------------------------------- ### render! Source: https://docs.rs/minijinja/latest/minijinja/macro.render.html A macro for rendering MiniJinja templates into strings. It supports two forms: one with a default environment and one with a custom environment. Context variables can be passed explicitly or by name. ```APIDOC ## render! ### Description A macro similar to `format!` but that uses MiniJinja for rendering. It can be used to quickly render a MiniJinja template into a string without having to create an environment first. The template is re-parsed every time the macro is called, which can be potentially slow. ### Method Macro invocation ### Signature ```rust macro_rules! render { ( in $env:expr, $tmpl:expr $(, $key:ident $(=> $value:expr)?)* $(,)? ) => { ... }; ( $tmpl:expr $(, $key:ident $(=> $value:expr)?)* $(,)? ) => { ... }; } ``` ### Parameters #### Environment (optional) - `$env` (expression) - Optional - The environment to use for rendering. If provided, the macro uses this environment instead of a default one. #### Template - `$tmpl` (expression) - Required - The template source string to render. #### Context Variables - `$key` (identifier) - Required - The variable name to pass to the template. Can be followed by `=> $value` to explicitly provide a value, or the value is taken from a variable with the same name in scope. ### Examples Passing context explicitly: ```rust println!("{}", render!("Hello {{ name }}!", name => "World")); ``` Passing variables with the default name: ```rust let name = "World"; println!("{}", render!("Hello {{ name }}!", name)); ``` Passing an explicit environment: ```rust let env = Environment::new(); println!("{}", render!(in env, "Hello {{ name }}!", name => "World")); ``` ### Panics This macro panics if the format string is an invalid template or the template evaluation failed. ``` -------------------------------- ### is_empty() example Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html Returns true if the slice has a length of 0. The example asserts that a non-empty array is not empty and an empty slice is empty. ```rust let a = [1, 2, 3]; assert!(!a.is_empty()); let b: &[i32] = &[]; assert!(b.is_empty()); ``` -------------------------------- ### perform_test example Source: https://docs.rs/minijinja/latest/minijinja/struct.State.html Invokes a test function on a value. The example calls the 'even' test on the integer 42 and asserts the result is true. ```rust let rv = state.perform_test("even", &[42i32.into()]).unwrap(); assert!(rv); ``` -------------------------------- ### set_temp example Source: https://docs.rs/minijinja/latest/src/minijinja/vm/state.rs.html Shows how to use `set_temp` to store a new value under a name and return it. The snippet is part of the documentation for `set_temp` and demonstrates updating a counter stored as a temp. ```rust let new = Value::from(i64::try_from(old).unwrap() + 1); state.set_temp("my_counter", new.clone()); new ``` -------------------------------- ### is_number template usage examples Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_number.html Jinja template examples showing that `is_number` returns true for numeric values and false for strings. ```jinja {{ 42 is number }} -> true {{ "42" is number }} -> false ``` -------------------------------- ### Include first existing template from list Source: https://docs.rs/minijinja/latest/src/minijinja/syntax.rs.html Provides a list of templates checked for existence; the first existing one is included. With ignore missing, falls back to rendering nothing if none exist; otherwise fails with an error. ```jinja {% include ['page_detailed.html', 'page.html'] %} {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %} ``` -------------------------------- ### Usage example of max filter Source: https://docs.rs/minijinja/latest/minijinja/filters/fn.max.html Example showing how to use the `max` filter in a template. It returns the largest item from the iterable, here 4. ```jinja {{ [1, 2, 3, 4]|max }} -> 4 ``` -------------------------------- ### Render template with context! macro Source: https://docs.rs/minijinja/latest/minijinja/struct.Template.html Renders a template named "hello" using the context! macro to provide a name variable. The result is printed to stdout. ```rust let tmpl = env.get_template("hello").unwrap(); println!("{}", tmpl.render(context!(name => "John")).unwrap()); ``` -------------------------------- ### Disable lstrip_blocks with plus sign at block start Source: https://docs.rs/minijinja/latest/minijinja/syntax/index.html Manually disables lstrip_blocks for a block by putting a plus sign (+) at the start of the block. ```jinja
{%+ if something %}yay{% endif %}
``` -------------------------------- ### join filter usage example Source: https://docs.rs/minijinja/latest/minijinja/filters/fn.join.html Example usage of the join filter in a template. It joins the sequence with the given separator and outputs the result in lowercase. ```jinja {{ "Foo Bar Baz" | join(", ") }} -> foo, bar, baz ``` -------------------------------- ### bool filter example: 42 -> true Source: https://docs.rs/minijinja/latest/src/minijinja/filters.rs.html Converts a value into a boolean using the same truthiness rules as the if statement. The example shows that 42 evaluates to true. ```jinja {{ 42|bool }} -> true ```