### Capitalize Filter Example Source: https://askama.rs/en/stable/filters.html Provides a concrete example of the 'capitalize' filter's output. ```Askama {{ "hello" | capitalize }} ``` -------------------------------- ### Check Block Start Syntax Source: https://askama.rs/en/stable/doc/src/askama_parser/node.rs.html Ensures that a block node starts correctly and handles cases where the block is unexpectedly empty. ```rust fn check_block_start<'a: 'l, 'l>( i: &mut InputStream<'a, 'l>, start: Span, node: &str, expected: &str, ) -> ParseResult<'a, ()> { if i.is_empty() { return cut_error!( format!("expected `{expected}` to terminate `{node}` node, found nothing"), start, ); } i.state.syntax.block_start.void().parse_next(i) } ``` -------------------------------- ### Span::start() - Get an empty Span at the start Source: https://askama.rs/en/stable/doc/askama_parser/struct.Span.html Returns an empty Span that points to the start of the current Span. ```rust pub fn start(self) -> Self ``` -------------------------------- ### Center Filter Example Source: https://askama.rs/en/stable/filters.html Demonstrates the 'center' filter with a specific width, showing the resulting padding. ```Askama -{{ "a" | center(5) }}- ``` -------------------------------- ### Askama Template Parse Tree Example Source: https://askama.rs/en/stable/print.html This is an example of the parse tree output for a simple Askama template, showing literal strings and expressions. ```text [Lit("", "Hello,", " "), Expr(WS(false, false), Var("name")), Lit("", "!", "\n")] ``` -------------------------------- ### Askama Generated Rust Code Example Source: https://askama.rs/en/stable/debugging.html This is an example of the Rust code generated by Askama for a template. It shows the `render_into` implementation that writes the template content to a writer. ```rust impl<'a> askama::Template for HelloWorld<'a> { fn render_into(&self, __askama_writer: &mut AskamaW) -> askama::Result<()> where AskamaW: core::fmt::Write + ?Sized, { __askama_writer.write_str("Hello, ")?; match ( &((&&askama::filters::AutoEscaper::new( &(self.name), askama::filters::Html, )) .askama_auto_escape()?), ) { (expr2,) => { (&&askama::filters::Writable(expr2)).askama_write(__askama_writer)?; } } __askama_writer.write_str("!")?; Ok(()) } const SIZE_HINT: usize = 11usize; } ``` -------------------------------- ### Basic HTML Template Example Source: https://askama.rs/en/stable/introduction.html Create a simple HTML template file named 'hello.html' in the 'templates' directory. ```html Hello, {{ name }}! ``` -------------------------------- ### Askama `upper` Filter Example Implementation Source: https://askama.rs/en/stable/doc/askama/filters/fn.upper.html Provides a Rust example showing the `upper` filter in action. It defines a template struct and asserts that the output is correctly uppercased for different input strings. ```rust /// ```jinja ///
{{ word|upper }}
/// ``` #[derive(Template)] #[template(ext = "html", in_doc = true)] struct Example<'a> { word: &'a str, } assert_eq!( Example { word: "foo" }.to_string(), "
FOO
" ); assert_eq!( Example { word: "FooBar" }.to_string(), "
FOOBAR
" ); ``` -------------------------------- ### Example Usage and Assertion for wordcount Filter Source: https://askama.rs/en/stable/doc/askama/filters/fn.wordcount.html This Rust code provides a complete example of using the 'wordcount' filter. It defines a template struct 'Example', instantiates it with a sample string, renders the template, and asserts that the output matches the expected word count. ```rust /// ```jinja ///
{{ example|wordcount }}
/// ``` #[derive(Template)] #[template(ext = "html", in_doc = true)] struct Example<'a> { example: &'a str, } assert_eq!( Example { example: "askama is sort of cool" }.to_string(), "
5
" ); ``` -------------------------------- ### Example: Serializing a Vec<&str> to JSON Source: https://askama.rs/en/stable/doc/src/askama/filters/json.rs.html A complete Askama template example demonstrating the `json` filter's usage with a `Vec<&str>`. The output is embedded within an HTML structure. ```rust # #[cfg(feature = "code-in-doc")] { # use askama::Template; /// ```jinja ///
  • Example
  • /// ``` #[derive(Template)] #[template(ext = "html", in_doc = true)] struct Example<'a> { data: Vec<&'a str>, } assert_eq!( Example { data: vec!["foo", "bar"] }.to_string(), "
  • Example
  • " ); # } ``` -------------------------------- ### Askama Template Parse Tree Example Source: https://askama.rs/en/stable/debugging.html This is an example of the parse tree output for a simple Askama template. It represents the structure of the template before code generation. ```text [Lit("", "Hello, ", " "), Expr(WS(false, false), Var("name")), Lit("", "!", "\n")] ``` -------------------------------- ### Deref Filter Example with Ref Source: https://askama.rs/en/stable/filters.html Demonstrates the 'deref' filter in a context where a reference is created using 'ref'. ```Askama {% let s = String::from("a") | ref %} {% if s | deref == String::from("b") %} {% endif %} ``` -------------------------------- ### Askama Template Example: urlencode Source: https://askama.rs/en/stable/doc/src/askama/filters/urlencode.rs.html A Rust code example showing how to use the `urlencode` filter within an Askama template. It asserts the expected output for a string containing a question mark. ```rust # #[cfg(feature = "code-in-doc")] { # use askama::Template; /// ```jinja ///
    {{ example|urlencode }}
    /// ``` #[derive(Template)] #[template(ext = "html", in_doc = true)] struct Example<'a> { example: &'a str, } assert_eq!( Example { example: "hello?world" }.to_string(), "
    hello%3Fworld
    " ); # } ``` -------------------------------- ### Example: Pretty-Printing Vec<&str> to JSON Source: https://askama.rs/en/stable/doc/src/askama/filters/json.rs.html An Askama template example showcasing the `json` filter with an indentation argument. It serializes a `Vec<&str>` into a nicely formatted JSON string within an HTML `
    `. ```rust # #[cfg(feature = "code-in-doc")] { # use askama::Template; /// ```jinja ///
    {{data|json(4)|safe}}
    /// ``` #[derive(Template)] #[template(ext = "html", in_doc = true)] struct Example<'a> { data: Vec<&'a str>, } assert_eq!( Example { data: vec!["foo", "bar"] }.to_string(), "
    [\n \"foo\",\n \"bar\"\n]
    " ); # } ``` -------------------------------- ### Rust Example of `center` filter usage Source: https://askama.rs/en/stable/doc/askama/filters/fn.center.html An example showing the `center` filter's output in a Rust Askama template. It asserts that a string 'a' centered to a width of 5 results in ' a ' when enclosed by hyphens. ```rust /// ```jinja ///
    -{{ example|center(5) }}-
    /// ``` #[derive(Template)] #[template(ext = "html", in_doc = true)] struct Example<'a> { example: &'a str, } assert_eq!( Example { example: "a" }.to_string(), "
    - a -
    " ); ``` -------------------------------- ### Result::or Example Source: https://askama.rs/en/stable/doc/askama/type.Result.html Demonstrates the behavior of the `or` method, which returns the first `Ok` value encountered or the last `Err` if all are `Err`. ```rust let x: Result = Ok(2); let y: Result = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("early error"); let y: Result = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("not a 2"); let y: Result = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result = Ok(2); let y: Result = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` -------------------------------- ### Assigned Or Filter Example with Option Source: https://askama.rs/en/stable/filters.html Illustrates the 'assigned_or' filter with an Option type, providing a fallback when the Option is None. ```Askama {% let greeting = Some("Hello") %} {{ greeting.as_ref() | assigned_or("Hi") }} ``` -------------------------------- ### Configuring Template Directories with Glob Syntax Source: https://askama.rs/en/stable/configuration.html Demonstrates using glob syntax in the `dirs` configuration to include templates from subdirectories. ```toml [general] dirs = ["templates/*"] ``` ```toml [general] dirs = ["templates/**"] ``` -------------------------------- ### Span::as_suffix_of() - Get substring as suffix Source: https://askama.rs/en/stable/doc/askama_parser/struct.Span.html Retrieves the substring from the source string starting from the Span's start position. ```rust pub fn as_suffix_of<'a>(&self, source: &'a str) -> Option<&'a str> ``` -------------------------------- ### Actix-web HTML Response Source: https://askama.rs/en/stable/frameworks.html Example of returning an HTML response from an Actix-web handler using Askama's render output. ```rust use actix_web::web::Html; use actix_web::{Responder, handler}; #[handler] fn handler() -> Result { … Ok(Html::new(template.render()?)) } ``` -------------------------------- ### Parse Expression Start Source: https://askama.rs/en/stable/doc/src/askama_parser/lib.rs.html Parses the start delimiter for an expression. ```rust fn expr_start<'a: 'l, 'l>(i: &mut InputStream<'a, 'l>) -> ParseResult<'a, ()> { i.state.syntax.expr_start.void().parse_next(i) } ``` -------------------------------- ### Parse Block Start Source: https://askama.rs/en/stable/doc/src/askama_parser/lib.rs.html Parses the start of a block construct within the input stream. ```rust fn block_start<'a: 'l, 'l>(i: &mut InputStream<'a, 'l>) -> ParseResult<'a, ()> { i.state.syntax.block_start.void().parse_next(i) } ``` -------------------------------- ### Configure Custom Syntax Definitions Source: https://askama.rs/en/stable/doc/src/askama_derive/config.rs.html Demonstrates how to define custom syntax configurations, including default syntax and specific delimiters for different syntaxes. ```rust #[cfg(feature = "config")] #[test] fn add_syntax() { let raw_config = r#" [general] default_syntax = "foo" [[syntax]] name = "foo" block_start = "{<" [[syntax]] name = "bar" expr_start = "{!" "#; let default_syntax = Syntax::default(); let config = Config::new(raw_config, None, None, None, None).unwrap(); assert_eq!(config.default_syntax, "foo"); let foo = config.syntaxes.get("foo").unwrap(); assert_eq!(foo.block_start, "{<"); assert_eq!(foo.block_end, default_syntax.block_end); assert_eq!(foo.expr_start, default_syntax.expr_start); assert_eq!(foo.expr_end, default_syntax.expr_end); assert_eq!(foo.comment_start, default_syntax.comment_start); assert_eq!(foo.comment_end, default_syntax.comment_end); let bar = config.syntaxes.get("bar").unwrap(); assert_eq!(bar.block_start, default_syntax.block_start); assert_eq!(bar.block_end, default_syntax.block_end); assert_eq!(bar.expr_start, "{!); assert_eq!(bar.expr_end, default_syntax.expr_end); assert_eq!(bar.comment_start, default_syntax.comment_start); assert_eq!(bar.comment_end, default_syntax.comment_end); } ``` -------------------------------- ### Rust Template Rendering Example Source: https://askama.rs/en/stable/template_syntax.html Demonstrates rendering a template that includes another template using Rust structs and Askama's Template derive macro. Shows how to pass data between templates. ```rust use askama::Template; #[derive(Template)] #[template(source = "Section 1: {{ s1 }}", ext = "txt")] struct RenderInPlace<'a> { s1: SectionOne<'a> } #[derive(Template)] #[template(source = "A={{ a }}\nB={{ b }}", ext = "txt")] struct SectionOne<'a> { a: &'a str, b: &'a str, } let t = RenderInPlace { s1: SectionOne { a: "a", b: "b" } }; assert_eq!(t.render().unwrap(), "Section 1: A=a\nB=b") ``` -------------------------------- ### Configure Template Directories with Glob Patterns Source: https://askama.rs/en/stable/doc/src/askama_derive/config.rs.html Demonstrates how to configure template directories using glob patterns. The first example shows top-level directory inclusion, while the second includes nested subdirectories. ```rust fn test_config_dirs_glob() { let root = manifest_root(); let config = Config::new( "[general]\ndirs = [\"templates/*\"]", None, None, None, None, ) .unwrap(); // We ensure that it includes only top level folders. assert_eq!(config.dirs, vec![root.join("templates/sub")]); let config = Config::new( "[general]\ndirs = [\"templates/**\"]", None, None, None, None, ) .unwrap(); // We ensure that it includes top level and sub-folders. assert_eq!( config.dirs, vec![root.join("templates/sub"), root.join("templates/sub/sub1")] ); } ``` -------------------------------- ### Span::no_span() - Create an empty Span at the start Source: https://askama.rs/en/stable/doc/askama_parser/struct.Span.html Creates an empty Span that points to the start of the string. This is a constant function. ```rust pub const fn no_span() -> Span ``` -------------------------------- ### SourceSpan Initialization Methods Source: https://askama.rs/en/stable/doc/src/askama_derive/spans.rs.html Provides methods to create SourceSpan instances. `empty()` creates a span at the call site. `from_source()` parses a string literal into a SpannedSource. `from_path()` creates a SpannedPath from a configuration literal. ```rust pub(crate) fn empty() -> SourceSpan { Self::Empty(Span::call_site()) } pub(crate) fn from_source(source: LitStr) -> Result<(String, Self), CompileError> { let (source, span) = SpannedSource::new(source)?; Ok((source, Self::Source(span))) } #[cfg(feature = "external-sources")] pub(crate) fn from_path(config: LitStr) -> Result { Ok(Self::Path(SpannedPath::new(config)?)) } ``` -------------------------------- ### Get Error Cause (Deprecated) Source: https://askama.rs/en/stable/doc/askama/enum.Error.html Deprecated method to get the cause of the error. Use `Error::source` which supports downcasting. ```rust fn cause(&self) -> Option<&dyn Error> ``` -------------------------------- ### Enable All Features with "full" Source: https://askama.rs/en/stable/features.html The `"full"` feature flag enables all implemented features, including `default`, `code-in-doc`, and `serde_json`, for a quick start. ```toml full = ["default", "code-in-doc", "serde_json"] ``` -------------------------------- ### Result::unwrap_err_unchecked Example (Ok - Undefined Behavior) Source: https://askama.rs/en/stable/doc/askama/type.Result.html Demonstrates the unsafe usage of `unwrap_err_unchecked` on an `Ok` variant, which leads to undefined behavior. ```rust let x: Result = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Askama Configuration: Glob Syntax for Template Directories Source: https://askama.rs/en/stable/print.html Use glob syntax in the `dirs` configuration to specify template locations, including subdirectories. ```toml [general] dirs = ["templates/*"] ``` ```toml [general] dirs = ["templates/**"] ``` -------------------------------- ### Get Error Description (Deprecated) Source: https://askama.rs/en/stable/doc/askama/enum.Error.html Deprecated method to get a string description of the error. Use the `Display` implementation or `to_string()` instead. ```rust fn description(&self) -> &str ``` -------------------------------- ### Import and Use Macro from External File Source: https://askama.rs/en/stable/template_syntax.html Demonstrates importing macros from an external file ('macro.html') using a named scope and then invoking the imported macro. ```askama {% import "macro.html" as scope %} {{ scope::heading("test") }} ``` -------------------------------- ### Configure Custom Syntax Definitions (Array Format) Source: https://askama.rs/en/stable/doc/src/askama_derive/config.rs.html Shows an alternative way to define custom syntax configurations using an array format for the 'syntax' key. ```rust #[cfg(feature = "config")] #[test] fn add_syntax_two() { let raw_config = r#" syntax = [{ name = "foo", block_start = "{<" }, { name = "bar", expr_start = "{!" } ] [general] default_syntax = "foo" "#; let default_syntax = Syntax::default(); let config = Config::new(raw_config, None, None, None, None).unwrap(); assert_eq!(config.default_syntax, "foo"); let foo = config.syntaxes.get("foo").unwrap(); assert_eq!(foo.block_start, "{<"); assert_eq!(foo.block_end, default_syntax.block_end); assert_eq!(foo.expr_start, default_syntax.expr_start); assert_eq!(foo.expr_end, default_syntax.expr_end); } ``` -------------------------------- ### Askama Default Configuration: Template Directories Source: https://askama.rs/en/stable/print.html Configure the directories Askama searches for templates using the `dirs` key in `askama.toml`. This example sets the search path to a 'templates' directory. ```toml [general] dirs = ["templates"] # Unless you add a `-` in a block, whitespace characters won't be trimmed. whitespace = "preserve" ``` -------------------------------- ### Getting Mutable References with `as_mut()` Source: https://askama.rs/en/stable/doc/askama/type.Result.html Shows how to use `as_mut()` to get mutable references to the contents of a `Result`. This enables in-place modification of the `Ok` or `Err` value. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Askama Template Example: urlencode_strict Source: https://askama.rs/en/stable/doc/src/askama/filters/urlencode.rs.html A Rust code example demonstrating the `urlencode_strict` filter in an Askama template. It asserts the output for a string containing forward slashes, which are encoded by this filter. ```rust # #[cfg(feature = "code-in-doc")] { # use askama::Template; /// ```jinja /// Example /// ``` #[derive(Template)] #[template(ext = "html", in_doc = true)] struct Example<'a> { example: &'a str, } assert_eq!( Example { example: "/hello/world" }.to_string(), "Example" ); # } ``` -------------------------------- ### Using filesizeformat Filter Source: https://askama.rs/en/stable/doc/askama/filters/fn.filesizeformat.html Demonstrates how to use the `filesizeformat` filter within an Askama template to display a byte size in a human-readable format. The filter takes the byte count and an optional precision argument. ```rust pub fn filesizeformat( bytes: u128, precision: u8, ) -> Result ``` ```rust #[derive(Template)] #[template( source = "Filesize: {{ size_in_bytes | filesizeformat }}.", ext = "html" )] struct Example { size_in_bytes: u64, } let tmpl = Example { size_in_bytes: 1_234_567 }; assert_eq!(tmpl.to_string(), "Filesize: 1.23 MB."); ``` -------------------------------- ### Specify Configuration File Path Source: https://askama.rs/en/stable/creating_templates.html Sets the path to a custom configuration file for Askama, relative to the crate root. ```rust #[derive(Template)] #[template(path = "hello.html", config = "config.toml")] struct HelloTemplate<'a> { ... } ``` -------------------------------- ### Creating a new Config instance Source: https://askama.rs/en/stable/doc/src/askama_derive/config.rs.html The `new` function initializes a `Config` instance, utilizing a static cache (`CACHE`) to store and retrieve configurations based on `OwnedConfigKey`. It handles cache lookups and inserts new configurations if not found. ```rust impl Config { pub(crate) fn new( source: &str, config_path: Option<&str>, template_whitespace: Option, config_span: Option, full_config_path: Option, ) -> Result<&'static Config, CompileError> { static CACHE: ManuallyDrop>> = ManuallyDrop::new(OnceLock::new()); CACHE.get_or_init(OnceMap::default).get_or_try_insert( &ConfigKey { root: Cow::Owned(manifest_root()), source: source.into(), config_path: config_path.map(Cow::Borrowed), template_whitespace, }, |key| { let config = Config::new_uncached(key.to_owned(), config_span, full_config_path)?; let config = &*Box::leak(Box::new(config)); Ok((config._key, config)) }, |config| *config, ) } fn new_uncached( key: OwnedConfigKey, config_span: Option, full_config_path: Option, ) -> Result { let s = key.0.source.as_ref(); let config_path = key.0.config_path.as_deref(); let root = key.0.root.as_ref(); let default_dirs = vec![root.join("templates")]; let mut syntaxes = HashMap::default(); syntaxes.insert(DEFAULT_SYNTAX_NAME.to_string(), SyntaxAndCache::default()); let raw = if s.is_empty() { RawConfig::default() } else { RawConfig::from_toml_str(s)? }; let (dirs, default_syntax, whitespace) = match raw.general { Some(General { dirs, default_syntax, whitespace, }) => ( dirs.map_or(default_dirs, |v| { v.into_iter() .flat_map(|dir| get_config_dirs(root, dir)) .collect() }), default_syntax.unwrap_or(DEFAULT_SYNTAX_NAME), whitespace, ), None => (default_dirs, DEFAULT_SYNTAX_NAME, Whitespace::default()), }; let file_info = config_path.map(|path| FileInfo::new(Path::new(path), None, None)); let whitespace = key.0.template_whitespace.unwrap_or(whitespace); if let Some(raw_syntaxes) = raw.syntax { for raw_s in raw_syntaxes { let name = raw_s.name; match syntaxes.entry(name.to_string()) { Entry::Vacant(entry) => { ``` -------------------------------- ### Example: JSON in `data-extra` attribute Source: https://askama.rs/en/stable/doc/askama/filters/fn.json.html A complete example demonstrating the `json` filter's use within a `data-extra` attribute in an HTML `
  • ` tag, including the Rust struct and assertion. ```rust /// ```jinja ///
  • Example
  • /// ``` #[derive(Template)] #[template(ext = "html", in_doc = true)] struct Example<'a> { data: Vec<&'a str>, } assert_eq!( Example { data: vec!["foo", "bar"] }.to_string(), "
  • Example
  • " ); ``` -------------------------------- ### Example Usage of strip_common Source: https://askama.rs/en/stable/doc/askama_parser/fn.strip_common.html Illustrates how `strip_common` works by showing an example where the base path is the current directory and the target path is a file within subdirectories. The function returns the relative path from the base. ```text current dir: /a/b/c path: /a/b/c/d/e.txt `strip_common` will return `d/e.txt`. ``` -------------------------------- ### Define and Render a Basic Askama Template Source: https://askama.rs/en/stable/doc/askama/index.html This snippet shows how to define a template using the `Template` derive macro with an inline source and render it. It demonstrates basic variable substitution and the default auto-escaping behavior. ```rust #[derive(Template)] #[template( ext = "html", source = "

    © {{ year }} {{ enterprise|upper }}

    " )] struct Footer<'a> { year: u16, enterprise: &'a str, } assert_eq!( Footer { year: 2025, enterprise: "Askama developers" }.to_string(), "

    © 2025 <EM>ASKAMA</EM> DEVELOPERS

    ", ); // In here you see can Askama's auto-escaping. You, the developer, // can easily disable the auto-escaping with the `|safe` filter, // but a malicious user cannot insert e.g. HTML scripts this way. ``` -------------------------------- ### Askama `format` filter example Source: https://askama.rs/en/stable/doc/src/askama/filters/alloc.rs.html Illustrates the `format` filter in Askama, which takes a format string as the first argument and subsequent values to be formatted. This filter is analogous to Rust's `format!()` macro and supports filter composition. ```rust # #[cfg(feature = "code-in-doc")] { # use askama::Template; /// ```jinja ///
    {{ "{:?}"|format(value) }}
    /// ``` #[derive(Template)] #[template(ext = "html", in_doc = true)] struct Example { value: (usize, usize), } assert_eq!( Example { value: (3, 4) }.to_string(), "
    (3, 4)
    " ); # } ``` -------------------------------- ### Example: Using the `backdoor` filter with MaybeSafe Source: https://askama.rs/en/stable/doc/src/askama/filters/escape.rs.html This example demonstrates a custom filter `backdoor` that uses `MaybeSafe` to conditionally escape its output. The template uses this filter to control whether a class attribute is escaped. ```Rust mod filters { use askama::{filters::MaybeSafe, Result, Values}; // Do not actually use this filter! It's an intentionally bad example. #[askama::filter_fn] pub fn backdoor( s: T, _: &dyn Values, enable: &bool, ) -> Result> { Ok(match *enable { true => MaybeSafe::Safe(s), false => MaybeSafe::NeedsEscaping(s), }) } } #[derive(askama::Template)] #[template( source = "
    ", ext = "html" )] struct DivWithBackdoor<'a> { klass: &'a str, enable_backdoor: bool, } assert_eq!( DivWithBackdoor { klass: "