### Retrieving Optional and Required Arguments Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Kwargs.html Examples of using the get method to fetch arguments from a Kwargs object, demonstrating how to handle both optional and required parameters. ```Rust // f(int=42) -> Some(42), f() -> None let optional_int: Option = kwargs.get("int")?; // f(int=42) -> 42, f() -> Error let required_int: u32 = kwargs.get("int")?; ``` -------------------------------- ### Getting Optional and Required Arguments with Kwargs in Rust Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Kwargs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides examples of using the `get` method on Kwargs to retrieve arguments. It demonstrates how to handle both optional arguments using `Option` and required arguments, where failure to provide the argument results in an error. ```rust // f(int=42) -> Some(42) // f() -> None let optional_int: Option = kwargs.get("int")?; // f(int=42) -> 42 // f() -> Error let required_int: u32 = kwargs.get("int")?; ``` -------------------------------- ### Example: Rendering with Default Named Variable Source: https://docs.rs/minijinja/latest/minijinja/macro.render.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows an example of using the `render!` macro where the context variable's name is inferred from a local variable. ```rust let name = "World"; println!("Hello {{ name }}!", name); ``` -------------------------------- ### Basic MiniJinja Template Example Source: https://docs.rs/minijinja/latest/minijinja/syntax/index.html?search=u32+-%3E+bool A minimal minijinja template demonstrating basic syntax including blocks, for loops, variable output, and comments. This example illustrates how to structure HTML content with dynamic data. ```html {% block title %}My Website{% endblock %}

My Webpage

{% block body %}{% endblock %} {# a comment #} ``` -------------------------------- ### minijinja render macro examples Source: https://docs.rs/minijinja/latest/minijinja/macro.render.html Demonstrates various ways to use the `render!` macro in MiniJinja. Examples show explicit context passing, default variable naming, and using a custom environment for template rendering. ```rust println!("{}", render!("Hello {{ name }}!", name => "World")); ``` ```rust let name = "World"; println!("{}", render!("Hello {{ name }}!", name)); ``` ```rust let env = Environment::new(); println!("{}", render!(in env, "Hello {{ name }}!", name => "World")); ``` -------------------------------- ### Basic MiniJinja Template Example Source: https://docs.rs/minijinja/latest/minijinja/syntax/index.html A minimal MiniJinja template demonstrating basic syntax, including blocks, for loops, and variable output. This example illustrates how to structure an HTML document with dynamic content. ```html {% block title %}My Website{% endblock %}

My Webpage

{% block body %}{% endblock %} {# a comment #} ``` -------------------------------- ### Initialize Environment and Add Templates Source: https://docs.rs/minijinja/latest/minijinja/struct.Environment.html Demonstrates how to create a new MiniJinja environment and add templates using both borrowed strings and owned strings. ```rust let mut env = Environment::new(); env.add_template("index.html", "Hello {{ name }}!").unwrap(); let mut env = Environment::new(); env.add_template_owned("index.html".to_string(), "Hello {{ name }}!".to_string()).unwrap(); ``` -------------------------------- ### Create minijinja Environment with Defaults Source: https://docs.rs/minijinja/latest/minijinja/struct.Environment.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates creating a new minijinja `Environment` with sensible default configurations, including built-in filters, tests, and globals. This is the most common way to initialize an environment. ```rust use minijinja::Environment; let mut env = Environment::new(); ``` -------------------------------- ### Initialize and Configure MiniJinja Environment Source: https://docs.rs/minijinja/latest/minijinja/struct.Environment.html?search= Demonstrates how to create a new environment and register a custom template loader to dynamically fetch templates. ```Rust fn create_env() -> Environment<'static> { let mut env = Environment::new(); env.set_loader(|name| { if name == "layout.html" { Ok(Some("...".into())) } else { Ok(None) } }); env } ``` -------------------------------- ### Get Block Delimiters from SyntaxConfig (Rust) Source: https://docs.rs/minijinja/latest/minijinja/syntax/struct.SyntaxConfig.html?search=u32+-%3E+bool Retrieves the configured start and end delimiters for template blocks. This function is part of the SyntaxConfig implementation and requires the 'custom_syntax' feature. ```rust pub fn block_delimiters(&self) -> (&str, &str) ``` -------------------------------- ### Jinja Template: Use unique filter to get distinct elements Source: https://docs.rs/minijinja/latest/minijinja/filters/fn.unique.html?search=std%3A%3Avec This Jinja template example demonstrates the usage of the `unique` filter to extract unique elements from a list. It shows how to apply the filter and then convert the result back into a list for display. The example assumes the `unique` filter is available, typically via a `builtins` feature flag. ```jinja {{ ['foo', 'bar', 'foobar', 'foobar']|unique|list }} -> ['foo', 'bar', 'foobar'] ``` -------------------------------- ### Get Comment Delimiters from SyntaxConfig (Rust) Source: https://docs.rs/minijinja/latest/minijinja/syntax/struct.SyntaxConfig.html?search=u32+-%3E+bool Returns the configured start and end delimiters for template comments. This method requires the 'custom_syntax' feature and provides access to the comment delimiter pair. ```rust pub fn comment_delimiters(&self) -> (&str, &str) ``` -------------------------------- ### Get Variable Delimiters from SyntaxConfig (Rust) Source: https://docs.rs/minijinja/latest/minijinja/syntax/struct.SyntaxConfig.html?search=u32+-%3E+bool Retrieves the configured start and end delimiters for template variables. This function is available with the 'custom_syntax' feature and returns a tuple of string slices representing the delimiters. ```rust pub fn variable_delimiters(&self) -> (&str, &str) ``` -------------------------------- ### Basic Template Rendering in Rust Source: https://docs.rs/minijinja/latest/minijinja/index.html?search= Demonstrates how to create a MiniJinja environment, add a template, and render it with a context. It shows the basic workflow for using MiniJinja in a Rust application. Requires the 'minijinja' crate. ```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()); ``` -------------------------------- ### Example: Rendering with Explicit Environment Source: https://docs.rs/minijinja/latest/minijinja/macro.render.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates how to use the `render!` macro with a custom `Environment` instance, providing more control over the rendering process. ```rust let env = Environment::new(); println!("Hello {{ name }}!", name => "World"); ``` -------------------------------- ### Rust: Handle Unaligned Element Offset Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html?search= This example demonstrates `element_offset` returning `None` when an element reference is not aligned with the start of a slice element. It highlights the difference between aligned and unaligned references within a flattened slice. ```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 ``` -------------------------------- ### Define and Add a Function with Optional Arguments Source: https://docs.rs/minijinja/latest/minijinja/functions/trait.Function.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This example defines a `substr` function that takes a string, a start index, and an optional end index. If the end index is not provided, it defaults to the string's length. The function is added as a filter to the Jinja environment. ```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); ``` -------------------------------- ### Example: Rendering with Explicit Context Source: https://docs.rs/minijinja/latest/minijinja/macro.render.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use the `render!` macro by explicitly passing a template string and a named context variable. ```rust println!("Hello {{ name }}!", name => "World"); ``` -------------------------------- ### Jinja Template: Use select filter Source: https://docs.rs/minijinja/latest/minijinja/filters/fn.select.html Example usage of the `select` filter in Jinja templates. The first example filters a list of numbers using the 'odd' test, and the second example filters a list of mixed types by their boolean evaluation. ```jinja {{ [1, 2, 3, 4]|select("odd") }} -> [1, 3] {{ [false, null, 42]|select }} -> [42] ``` -------------------------------- ### Split slice into chunks from the start Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Splits a slice into N-element arrays starting from the beginning, returning the chunks and a remainder. It panics if N is zero. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let (chunks, remainder) = slice.as_chunks(); assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]); assert_eq!(remainder, &['m']); ``` -------------------------------- ### Function: is_startingwith Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_startingwith.html?search=std%3A%3Avec Checks if a given string value starts with a specified prefix string. This function is available when the 'builtins' feature is enabled. ```APIDOC ## [FUNCTION] is_startingwith ### Description Checks if the provided value starts with the specified prefix string. Returns true if the condition is met, otherwise false. ### Method N/A (Template Function) ### Endpoint `is_startingwith(v: Cow<'_, str>, other: Cow<'_, str>)` ### Parameters #### Arguments - **v** (Cow<'_, str>) - Required - The string to be checked. - **other** (Cow<'_, str>) - Required - The prefix string to check against. ### Request Example ```jinja2 {{ "foobar" is startingwith "foo" }} ``` ### Response #### Success Response - **result** (bool) - Returns true if 'v' starts with 'other', false otherwise. #### Response Example ```json true ``` ``` -------------------------------- ### is_le Usage Example - Jinja Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_le.html?search= Examples demonstrating the usage of the is_le function (aliased as 'is le') within Jinja templates for direct comparison and with the 'select' filter. ```jinja {{ 1 is le 2 }} -> true {{ [1, 2, 3]|select("<= ", 2) }} => [1, 2] ``` -------------------------------- ### Example of using round filter in Jinja Source: https://docs.rs/minijinja/latest/minijinja/filters/fn.round.html?search= This example demonstrates how to use the `round` filter in a Jinja template. It takes a number and rounds it to the nearest whole number by default. ```jinja {{ 42.55|round }} -> 43.0 ``` -------------------------------- ### Configuring Syntax with SyntaxConfigBuilder Source: https://docs.rs/minijinja/latest/minijinja/syntax/struct.SyntaxConfigBuilder.html Demonstrates how to use the SyntaxConfigBuilder to define custom delimiters and prefixes for template parsing. The builder pattern allows chaining configuration methods before calling the build method to generate a SyntaxConfig instance. ```Rust use minijinja::syntax::SyntaxConfigBuilder; let mut builder = SyntaxConfig::builder(); builder.block_delimiters("{%", "%}") .variable_delimiters("{{", "}}") .line_statement_prefix("#"); let config = builder.build().unwrap(); ``` -------------------------------- ### Example Usage of is_undefined in minijinja Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_undefined.html?search= This example demonstrates how to use the `is_undefined` check within a minijinja template. It shows that a defined value like the integer 42 is not considered undefined. ```minijinja {{ 42 is undefined }} -> false ``` -------------------------------- ### Iterator Adapters for ValueIter Source: https://docs.rs/minijinja/latest/minijinja/value/struct.ValueIter.html Illustrates the use of various iterator adapters with ValueIter, such as step_by for controlled iteration, chain for combining iterators, and zip for pairing elements from two iterators. ```rust fn step_by(self, step: usize) -> StepBy fn chain(self, other: U) -> Chain::IntoIter> fn zip(self, other: U) -> Zip::IntoIter> ``` -------------------------------- ### Example usage of is_divisibleby in Jinja template Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_divisibleby.html?search=u32+-%3E+bool An example demonstrating how to use the is_divisibleby function within a Jinja template. This function returns true if the left-hand operand is divisible by the right-hand operand. ```jinja {{ 42 is divisibleby(2) }} -> true ``` -------------------------------- ### Load Templates into Environment Source: https://docs.rs/minijinja/latest/minijinja/struct.Environment.html?search= Shows how to add templates to the environment using both borrowed string slices and owned strings. ```Rust let mut env = Environment::new(); // Using borrowed strings env.add_template("index.html", "Hello {{ name }}!").unwrap(); // Using owned strings env.add_template_owned("index.html".to_string(), "Hello {{ name }}!".to_string()).unwrap(); ``` -------------------------------- ### Example Usage of is_boolean in Jinja Template Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_boolean.html This example demonstrates how to use the `is_boolean` function within a Jinja template rendered by minijinja. It checks if the literal value `true` is recognized as a boolean. ```jinja {{ true is boolean }} -> true ``` -------------------------------- ### Template Loading and Configuration Source: https://docs.rs/minijinja/latest/minijinja/struct.Environment.html?search= APIs for setting custom template loaders and configuring whitespace trimming behavior. ```APIDOC ## Template Loading and Configuration ### Description APIs for setting custom template loaders and configuring whitespace trimming behavior. ### `Environment::set_loader()` #### Description Registers a template loader function that allows the environment to dynamically load templates. #### Method `set_loader(&mut self, f: F)` #### Type Parameters - `F`: A closure or function that takes a template name (`&str`) and returns `Result, Error>`. #### Parameters - **f** (`F`) - Required - The template loader function. #### Example ```rust fn create_env() -> Environment<'static> { let mut env = Environment::new(); env.set_loader(|name| { if name == "layout.html" { Ok(Some("...".into())) } else { Ok(None) } }); env } ``` ### `Environment::set_keep_trailing_newline()` #### Description Configures whether to preserve the trailing newline when rendering templates. Affects future template loads. #### Method `set_keep_trailing_newline(&mut self, yes: bool)` #### Parameters - **yes** (`bool`) - Required - `true` to keep the trailing newline, `false` to strip it (default). ### `Environment::keep_trailing_newline()` #### Description Returns the current setting for preserving trailing newlines. #### Method `keep_trailing_newline(&self) -> bool` #### Returns `bool` - `true` if trailing newlines are preserved, `false` otherwise. ### `Environment::set_trim_blocks()` #### Description Configures whether to remove the first newline immediately following a block tag. Affects future template loads. #### Method `set_trim_blocks(&mut self, yes: bool)` #### Parameters - **yes** (`bool`) - Required - `true` to trim the first newline after a block, `false` otherwise (default). ### `Environment::trim_blocks()` #### Description Returns the current setting for trimming the first newline after a block. #### Method `trim_blocks(&self) -> bool` #### Returns `bool` - `true` if the first newline after a block is trimmed, `false` otherwise. ### `Environment::set_lstrip_blocks()` #### Description Configures whether to remove leading whitespace (spaces and tabs) from the start of a line up to a block tag. Affects future template loads. #### Method `set_lstrip_blocks(&mut self, yes: bool)` #### Parameters - **yes** (`bool`) - Required - `true` to strip leading whitespace before a block, `false` otherwise. ### `Environment::lstrip_blocks()` #### Description Returns the current setting for stripping leading whitespace before a block. #### Method `lstrip_blocks(&self) -> bool` #### Returns `bool` - `true` if leading whitespace before a block is stripped, `false` otherwise. ``` -------------------------------- ### Example Usage of Split Filter in Jinja Templates Source: https://docs.rs/minijinja/latest/minijinja/filters/fn.split.html?search= Demonstrates how to use the split filter in Jinja templates. The first example splits by whitespace, and the second splits by a comma. The result is converted to a list. ```jinja {{ "hello world"|split|list }} -> ["hello", "world"] {{ "c,s,v"|split(",")|list }} -> ["c", "s", "v"] ``` -------------------------------- ### CloneToUninit API Source: https://docs.rs/minijinja/latest/minijinja/struct.Environment.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides an unsafe method `clone_to_uninit` for performing copy-assignment from self to a mutable pointer destination. This is a nightly-only experimental API. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. ### Method `unsafe fn` ### Endpoint N/A (Method within an implementation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A ### Response #### Success Response (200) N/A (This is a method, not an API endpoint) #### Response Example N/A ``` -------------------------------- ### Configuration Methods Source: https://docs.rs/minijinja/latest/minijinja/struct.Environment.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Methods to configure the environment behavior such as auto-escaping, undefined values, and custom formatting. ```APIDOC ## PUT /environment/config ### Description Updates the configuration settings for the template engine environment. ### Parameters #### Request Body - **auto_escape_callback** (function) - Optional - Function to determine auto-escaping based on template name. - **undefined_behavior** (enum) - Optional - Sets how 'undefined' values are handled (e.g., Lenient). - **formatter** (function) - Optional - Custom function to format values into the output. - **debug** (bool) - Optional - Enable/disable debug mode (requires 'debug' feature). - **fuel** (u64) - Optional - Set instruction execution limit (requires 'fuel' feature). - **syntax** (SyntaxConfig) - Optional - Configure custom syntax (requires 'custom_syntax' feature). ### Response #### Success Response (200) - **status** (string) - Configuration updated successfully. ``` -------------------------------- ### Get Reference to Underlying Array (Rust) Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html?search= Attempts to get a reference to the underlying fixed-size array. Returns `Some` if the requested size `N` exactly matches the slice length, otherwise returns `None`. ```rust let slice = &[1, 2, 3]; let array_ref: Option<&[i32; 3]> = slice.as_array(); let wrong_size_ref: Option<&[i32; 2]> = slice.as_array(); assert!(array_ref.is_some()); assert!(wrong_size_ref.is_none()); ``` -------------------------------- ### Create a SyntaxConfig Builder (Rust) Source: https://docs.rs/minijinja/latest/minijinja/syntax/struct.SyntaxConfig.html?search=u32+-%3E+bool Initializes a builder for creating a custom SyntaxConfig. This method is available when the 'custom_syntax' feature is enabled and is the starting point for defining custom delimiters. ```rust pub fn builder() -> SyntaxConfigBuilder ``` -------------------------------- ### mapped_enumerator Example - Rust Source: https://docs.rs/minijinja/latest/minijinja/value/trait.ObjectExt.html?search=u32+-%3E+bool Demonstrates how to use the mapped_enumerator method to create a custom iterator enumeration for a struct implementing the Object trait. This example shows projecting keys from a HashMap into Value objects. ```rust use std::sync::Arc; use minijinja::value::{Value, Object, ObjectExt, Enumerator}; use std::collections::HashMap; #[derive(Debug)] struct CustomMap(HashMap); impl Object for CustomMap { fn get_value(self: &Arc, key: &Value) -> Option { self.0.get(&key.as_usize()?).copied().map(Value::from) } fn enumerate(self: &Arc) -> Enumerator { self.mapped_enumerator(|this| { Box::new(this.0.keys().copied().map(Value::from)) }) } } ``` -------------------------------- ### Serde Serialization and Deserialization Source: https://docs.rs/minijinja/latest/minijinja/value/index.html?search= Demonstrates converting data to Values using Serde and deserializing Values back into Rust structures. ```rust // Serialization let value = Value::from_serialize(&[1, 2, 3]); // Deserialization use serde::Deserialize; let value = Value::from(vec![1, 2, 3]); let vec = Vec::::deserialize(value).unwrap(); ``` -------------------------------- ### Jinja Template: is_le Usage Example Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_le.html Example of using the is_le function (aliased as 'is le') in a Jinja template. It demonstrates a direct comparison and its use with the 'select' filter for filtering lists. ```jinja {{ 1 is le 2 }} {{ [1, 2, 3]|select("<=, 2) }} ``` -------------------------------- ### Importing Macros and Variables with {% import %} Source: https://docs.rs/minijinja/latest/minijinja/syntax/index.html?search= Explains how to import macros and variables from other templates using `{% import %}` and `{% from ... import ... %}` syntax. Imports can be aliased, and entire modules can be imported using `{% import ... as ... %}`. Imported modules only contain explicitly defined variables and macros. ```html {% from "my_template.html" import my_macro, my_variable %} ``` ```html {% from "my_template.html" import my_macro as other_name %} {{ other_name() }} ``` ```html {% import "my_template.html" as helpers %} {{ helpers.my_macro() }} ``` -------------------------------- ### Including and Importing Templates in MiniJinja Source: https://docs.rs/minijinja/latest/minijinja/syntax/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to include content from other templates using the `{% include %}` tag and import variables or macros using `{% import %}` and `{% from %}`. The `include` tag supports ignoring missing files and including from a list of templates. Imports do not cache and have access to the full context. ```html {% include 'header.html' %} Body {% include 'footer.html' %} ``` ```html {% include 'customization.html' ignore missing %} ``` ```html {% include ['page_detailed.html', 'page.html'] %} {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %} ``` ```html {% from "my_template.html" import my_macro, my_variable %} ``` ```html {% from "my_template.html" import my_macro as other_name %} {{ other_name() }} ``` ```html {% import "my_template.html" as helpers %} {{ helpers.my_macro() }} ``` -------------------------------- ### Render Template to String in Rust Source: https://docs.rs/minijinja/latest/minijinja/struct.Template.html?search= Demonstrates how to retrieve a template from an environment and render it into a string using a context created with the context! macro. ```Rust let tmpl = env.get_template("hello").unwrap(); println!("{}", tmpl.render(context!(name => "John")).unwrap()); ``` -------------------------------- ### Jinja-like: selectattr Filter Usage Examples Source: https://docs.rs/minijinja/latest/minijinja/filters/fn.selectattr.html?search= Examples demonstrating the usage of the `selectattr` filter, similar to Jinja2. It filters a list of users based on an attribute's truthiness or a named test applied to an attribute. ```jinja {{ users|selectattr("is_active") }} {{ users|selectattr("id", "even") }} ``` -------------------------------- ### Example Usage of min Filter in Jinja Source: https://docs.rs/minijinja/latest/minijinja/filters/fn.min.html This example demonstrates how to use the `min` filter in Jinja templating to find the smallest number in a list. The filter is applied to a list of integers, and the result is the minimum value. ```jinja {{ [1, 2, 3, 4]|min }} -> 1 ``` -------------------------------- ### Environment Creation Source: https://docs.rs/minijinja/latest/minijinja/struct.Environment.html?search= Methods for creating new Minijinja environments with default or empty configurations. ```APIDOC ## Environment Creation ### Description Methods for creating new Minijinja environments. ### `Environment::new()` #### Description Creates a new environment with sensible defaults, including built-in filters, tests, and globals. #### Method `new()` #### Returns `Environment<'source>` - A new environment instance. ### `Environment::empty()` #### Description Creates a completely empty environment with no pre-configured filters, templates, or globals. #### Method `empty()` #### Returns `Environment<'source>` - A new, empty environment instance. ``` -------------------------------- ### is_lt Usage Examples (Jinja) Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_lt.html?search= Examples demonstrating the usage of the is_lt function within Jinja templates. It shows a direct comparison and its use with the 'select' filter for filtering lists based on a condition. The function is aliased to 'lessthan' and '<'. ```jinja {{ 1 is lt 2 }} -> true {{ [1, 2, 3]|select("<", 2) }} => [1] ``` -------------------------------- ### Configure minijinja Syntax with Custom Delimiters (Rust) Source: https://docs.rs/minijinja/latest/minijinja/syntax/struct.SyntaxConfig.html?search=u32+-%3E+bool Demonstrates how to set custom delimiters for blocks, variables, and comments in a minijinja environment using the SyntaxConfig builder. This requires the 'custom_syntax' feature to be enabled. It shows the process of creating an Environment, setting the syntax configuration, and building it. ```rust use minijinja::{Environment, SyntaxConfig}; let mut environment = Environment::new(); environment.set_syntax( SyntaxConfig::builder() .block_delimiters("\\BLOCK{", "}") .variable_delimiters("\\VAR{", "}") .comment_delimiters("\\#{", "}") .build() .unwrap() ); ``` -------------------------------- ### path_loader Function Source: https://docs.rs/minijinja/latest/minijinja/fn.path_loader.html?search=u32+-%3E+bool The `path_loader` function is a helper that creates a dynamic template loader for the Minijinja environment. It allows templates to be loaded from a specified directory on the filesystem. Templates starting with a dot or located in directories starting with a dot are excluded. ```APIDOC ## Function path_loader ### Description Helper to load templates from a given directory. This creates a dynamic loader which looks up templates in the given directory. Templates that start with a dot (`.`) or are contained in a folder starting with a dot cannot be loaded. ### Signature ```rust pub fn path_loader<'x, P: AsRef + 'x>( dir: P, ) -> impl for<'a> Fn(&'a str) -> Result, Error> + Send + Sync + 'static ``` ### Example ```rust fn create_env() -> Environment<'static> { let mut env = Environment::new(); env.set_loader(path_loader("path/to/templates")); env } ``` ``` -------------------------------- ### Configure Syntax Delimiters and Prefixes with SyntaxConfigBuilder Source: https://docs.rs/minijinja/latest/minijinja/syntax/struct.SyntaxConfigBuilder.html?search=std%3A%3Avec This snippet demonstrates the builder methods available for configuring custom syntax in MiniJinja. It includes methods for setting delimiters for blocks, variables, and comments, as well as defining prefixes for line-based statements and comments. ```rust pub struct SyntaxConfigBuilder { /* private fields */ } impl SyntaxConfigBuilder { pub fn block_delimiters(&mut self, s: S, e: E) -> &mut Self where S: Into>, E: Into>; pub fn variable_delimiters(&mut self, s: S, e: E) -> &mut Self where S: Into>, E: Into>; pub fn comment_delimiters(&mut self, s: S, e: E) -> &mut Self where S: Into>, E: Into>; pub fn line_statement_prefix(&mut self, s: S) -> &mut Self where S: Into>; pub fn line_comment_prefix(&mut self, s: S) -> &mut Self where S: Into>; pub fn build(&self) -> Result; } ``` -------------------------------- ### Get Mutable Reference to Underlying Array (Rust) Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html?search= Attempts to get a mutable reference to the underlying fixed-size array. Returns `Some` if the requested size `N` exactly matches the slice length, otherwise returns `None`. ```rust let mut slice = &mut [1, 2, 3]; let array_mut_ref: Option<&mut [i32; 3]> = slice.as_mut_array(); if let Some(arr) = array_mut_ref { arr[0] = 10; } assert_eq!(slice, &mut [10, 2, 3]); ``` -------------------------------- ### Including Templates with {% include %} Source: https://docs.rs/minijinja/latest/minijinja/syntax/index.html?search= Shows how to include the rendered content of another template into the current one using the `{% include %}` tag. It supports ignoring missing templates with `ignore missing` and including the first existing template from a list. ```html {% include 'header.html' %} Body {% include 'footer.html' %} ``` ```html {% include 'customization.html' ignore missing %} ``` ```html {% include ['page_detailed.html', 'page.html'] %} {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %} ``` -------------------------------- ### CloneToUninit Trait Source: https://docs.rs/minijinja/latest/minijinja/struct.Environment.html?search= Experimental nightly-only API for performing copy-assignment from a source to an uninitialized destination pointer. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. This is a nightly-only experimental API. ### Method N/A (Rust Function) ### Parameters #### Path Parameters - **dest** (*mut u8) - Required - A pointer to the uninitialized memory destination. ### Response #### Success Response - **void** - Performs the copy operation in-place. ``` -------------------------------- ### Get Unchecked Element/Subslice Reference (Rust) Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html?search= Retrieves a reference to an element or subslice without bounds checking. This method is unsafe and requires careful handling to avoid undefined behavior. It's analogous to `get(index).unwrap_unchecked()`. ```rust let x = &[1, 2, 4]; unsafe { assert_eq!(x.get_unchecked(1), &2); } ``` -------------------------------- ### Initialize Vec using Raw Pointers (Rust) Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html?search= Demonstrates initializing a Vec's elements using raw pointer writes and then setting the length. This method requires `unsafe` and careful management of memory to avoid undefined behavior. It's useful when direct memory manipulation is necessary. ```rust #![feature(box_vec_non_null)] // Allocate vector big enough for 4 elements. let size = 4; let mut x: Vec = Vec::with_capacity(size); let x_ptr = x.as_mut_ptr(); // Initialize elements via raw pointer writes, then set length. unsafe { for i in 0..size { *x_ptr.add(i) = i as i32; } x.set_len(size); } assert_eq!(&*x, &[0, 1, 2, 3]); ``` -------------------------------- ### Example Usage of is_safe Filter in Jinja Templates Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_safe.html Demonstrates how to use the `is_safe` filter within a Jinja template to check if a string is safe. The example shows that an escaped string is considered safe. This filter is also aliased as `escaped`. ```jinja {{ ""|escape is safe }} ``` -------------------------------- ### PUT /environment/configuration Source: https://docs.rs/minijinja/latest/minijinja/struct.Environment.html Methods for configuring rendering behaviors such as whitespace handling and template loading. ```APIDOC ## PUT /environment/configuration ### Description Updates the environment configuration flags including trailing newline preservation, block trimming, and loader registration. ### Method PUT ### Parameters #### Request Body - **keep_trailing_newline** (bool) - Optional - Preserve trailing newline in output. - **trim_blocks** (bool) - Optional - Remove first newline after a block. - **lstrip_blocks** (bool) - Optional - Remove leading spaces/tabs before block tags. ### Request Example { "trim_blocks": true, "keep_trailing_newline": false } ### Response #### Success Response (200) - **status** (string) - Configuration updated successfully. ``` -------------------------------- ### Example Usage of int Filter in Jinja Template Source: https://docs.rs/minijinja/latest/minijinja/filters/fn.int.html This example demonstrates how to use the `int` filter within a Jinja template to convert a string representation of a number into an actual integer for comparison. The filter is applied using the pipe symbol `|`. ```jinja {{ "42"|int == 42 }} ``` -------------------------------- ### Example usage of is_ne and select filter in Jinja Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_ne.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates the usage of the is_ne function (aliased as '!=') and the 'select' filter in Jinja templating. The first example shows a direct inequality check, while the second shows filtering a list based on inequality. ```jinja {{ 2 is ne 1 }} -> true {{ [1, 2, 3]|select("!=", 1) }} => [2, 3] ``` -------------------------------- ### POST /render_str Source: https://docs.rs/minijinja/latest/minijinja/struct.Environment.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Parses and renders a template directly from a string input. ```APIDOC ## POST /render_str ### Description Parses and renders a template from a string in one go. The internal name of the template is set to ``. ### Method POST ### Endpoint /render_str ### Parameters #### Request Body - **source** (string) - Required - The template string to render. - **ctx** (Serialize) - Required - The context data to pass to the template. ### Response #### Success Response (200) - **result** (string) - The rendered template output. #### Response Example { "result": "Hello World" } ``` -------------------------------- ### Example Usage of is_eq in Jinja Template Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_eq.html?search= Demonstrates the usage of the 'is_eq' function within a Jinja template. The first example shows a direct equality check, while the second illustrates its use with the 'select' filter for filtering a list based on a condition. ```jinja {{ 1 is eq 1 }} -> true {{ [1, 2, 3]|select("==", 1) }} => [1] ``` -------------------------------- ### Minijinja Macros Source: https://docs.rs/minijinja/latest/minijinja/all.html?search=std%3A%3Avec Lists the available macros within the Minijinja library. ```APIDOC ## Macros ### Description Provides convenient ways to define template contexts and arguments. ### Available Macros - **args**: Macro for creating argument maps. - **context**: Macro for creating template rendering contexts. - **render**: Macro for rendering templates with a given context. ``` -------------------------------- ### Configure Syntax using SyntaxConfigBuilder Source: https://docs.rs/minijinja/latest/minijinja/syntax/struct.SyntaxConfigBuilder.html?search=u32+-%3E+bool Demonstrates how to use the SyntaxConfigBuilder to define custom delimiters and prefixes for a template engine. The builder methods return a mutable reference to self, allowing for chained configuration, and the build method produces the final SyntaxConfig. ```rust use minijinja::syntax::SyntaxConfigBuilder; let mut builder = SyntaxConfig::builder(); builder .block_delimiters("{%", "%}") .variable_delimiters("{{", "}}") .comment_delimiters("{#", "#}") .line_statement_prefix("##") .line_comment_prefix("#"); let config = builder.build().expect("Failed to build syntax config"); ``` -------------------------------- ### Example Usage of title Filter in Jinja Template Source: https://docs.rs/minijinja/latest/minijinja/filters/fn.title.html?search=u32+-%3E+bool This example demonstrates how to use the `title` filter within a Jinja template rendered by minijinja. The filter is applied to the `chapter.title` variable to convert its value to title case before rendering it within an H1 tag. ```jinja

{{ chapter.title|title }}

``` -------------------------------- ### Get Length of Value in Jinja Template (Rust) Source: https://docs.rs/minijinja/latest/minijinja/filters/fn.length.html This snippet demonstrates how to use the `length` filter in a Jinja template rendered with Rust's minijinja library. The filter is applied to a variable to get its length. It requires the 'builtins' feature to be enabled. ```jinja

Search results: {{ results|length }} ``` -------------------------------- ### is_startingwith Function Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_startingwith.html?search=u32+-%3E+bool Checks if a given string starts with a specified prefix. This function is part of the minijinja crate's built-in functions and requires the 'builtins' feature to be enabled. ```APIDOC ## is_startingwith ### Description Checks if the value is starting with a string. ### Method N/A (This is a function, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```jinja {{ "foobar" is startingwith "foo" }} {{ "foobar" is startingwith "bar" }} ``` ### Response #### Success Response (N/A) Returns a boolean value: `true` if the string starts with the prefix, `false` otherwise. #### Response Example ```json true false ``` ### Notes - Available on `crate feature 'builtins'` only. - The function signature is `pub fn is_startingwith(v: Cow<'_, str>, other: Cow<'_, str>) -> bool`. ``` -------------------------------- ### strip_prefix Source: https://docs.rs/minijinja/latest/minijinja/value/struct.Rest.html?search=u32+-%3E+bool Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ```APIDOC ## pub fn strip_prefix

(&self, prefix: &P) -> Option<&[T]> ### Description Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ### Method `GET` (conceptually, as it reads data) ### Endpoint N/A (method on slice) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```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())); ``` ### Response #### Success Response (200) `Option<&[T]>`: `Some` containing the subslice after the prefix if it exists, otherwise `None`. #### Response Example ```json { "example": "Some(&[40, 30][..])" } ``` ``` -------------------------------- ### Serde Serialization and Deserialization Source: https://docs.rs/minijinja/latest/minijinja/value/index.html Demonstrates converting Rust types to Values via Serde and deserializing Values back into Rust types. ```Rust let value = Value::from_serialize(&[1, 2, 3]); use serde::Deserialize; let value = Value::from(vec![1, 2, 3]); let vec = Vec::::deserialize(value).unwrap(); ``` -------------------------------- ### Check if String Starts With Another (Rust) Source: https://docs.rs/minijinja/latest/minijinja/tests/fn.is_startingwith.html The `is_startingwith` function checks if the first string argument starts with the second string argument. This function is part of the minijinja crate and requires the 'builtins' feature to be enabled. It takes two `Cow<'_, str>` arguments and returns a boolean. ```rust pub fn is_startingwith(v: Cow<'_, str>, other: Cow<'_, str>) -> bool ``` ```jinja {{ "foobar" is startingwith "foo" }} -> true {{ "foobar" is startingwith "bar" }} -> false ``` -------------------------------- ### Perform Test and Format Values in MiniJinja Source: https://docs.rs/minijinja/latest/minijinja/struct.State.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to invoke a test function on a value and format values into strings using the environment's formatter. ```rust let rv = state.perform_test("even", &[42i32.into()]).unwrap(); assert!(rv); let rv = state.format(Value::from(42)).unwrap(); assert_eq!(rv, "42"); ``` -------------------------------- ### CloneToUninit::clone_to_uninit Source: https://docs.rs/minijinja/latest/minijinja/value/struct.DynObject.html?search=std%3A%3Avec Performs a low-level copy-assignment from the current instance to an uninitialized memory destination. ```APIDOC ## [POST] /memory/clone_to_uninit ### Description Performs copy-assignment from self to a raw pointer destination. Note: This is a nightly-only experimental API. ### Method POST ### Endpoint /memory/clone_to_uninit ### Parameters #### Request Body - **dest** (*mut u8) - Required - A raw pointer to the uninitialized destination memory. ### Response #### Success Response (200) - **void** - Memory successfully copied. ```