mirror of
https://github.com/askama-rs/askama.git
synced 2025-09-30 14:31:36 +00:00

This commit introduces a shorthand for defining and calling macros when using them as a reusable substitute for variables assigned complex values (e.g. string literals with or without newline escapes). The use-case is formatting - from my experience it's easier to visually parse a `macro` `endmacro` block than a multiline variable assignment. Signed-off-by: mataha <mataha@users.noreply.github.com>
86 lines
1.8 KiB
Rust
86 lines
1.8 KiB
Rust
use askama::Template;
|
|
|
|
#[derive(Template)]
|
|
#[template(path = "macro.html")]
|
|
struct MacroTemplate<'a> {
|
|
s: &'a str,
|
|
}
|
|
|
|
#[test]
|
|
fn test_macro() {
|
|
let t = MacroTemplate { s: "foo" };
|
|
assert_eq!(t.render().unwrap(), "12foo foo foo34foo foo5");
|
|
}
|
|
|
|
#[derive(Template)]
|
|
#[template(path = "macro-no-args.html")]
|
|
struct MacroNoArgsTemplate;
|
|
|
|
#[test]
|
|
fn test_macro_no_args() {
|
|
let t = MacroNoArgsTemplate;
|
|
assert_eq!(t.render().unwrap(), "11the best thing111we've ever done11");
|
|
}
|
|
|
|
#[derive(Template)]
|
|
#[template(path = "import.html")]
|
|
struct ImportTemplate<'a> {
|
|
s: &'a str,
|
|
}
|
|
|
|
#[test]
|
|
fn test_import() {
|
|
let t = ImportTemplate { s: "foo" };
|
|
assert_eq!(t.render().unwrap(), "foo foo foo");
|
|
}
|
|
|
|
#[derive(Template)]
|
|
#[template(path = "deep-nested-macro.html")]
|
|
struct NestedTemplate;
|
|
|
|
#[test]
|
|
fn test_nested() {
|
|
let t = NestedTemplate;
|
|
assert_eq!(t.render().unwrap(), "foo");
|
|
}
|
|
|
|
#[derive(Template)]
|
|
#[template(path = "deep-import-parent.html")]
|
|
struct DeepImportTemplate;
|
|
|
|
#[test]
|
|
fn test_deep_import() {
|
|
let t = DeepImportTemplate;
|
|
assert_eq!(t.render().unwrap(), "foo");
|
|
}
|
|
|
|
#[derive(Template)]
|
|
#[template(path = "macro-short-circuit.html")]
|
|
struct ShortCircuitTemplate {}
|
|
|
|
#[test]
|
|
fn test_short_circuit() {
|
|
let t = ShortCircuitTemplate {};
|
|
assert_eq!(t.render().unwrap(), "truetruetruefalsetruetrue");
|
|
}
|
|
|
|
#[derive(Template)]
|
|
#[template(path = "nested-macro-args.html")]
|
|
struct NestedMacroArgsTemplate {}
|
|
|
|
#[test]
|
|
fn test_nested_macro_with_args() {
|
|
let t = NestedMacroArgsTemplate {};
|
|
assert_eq!(t.render().unwrap(), "first second");
|
|
}
|
|
|
|
#[derive(Template)]
|
|
#[template(path = "macro-import-str-cmp.html")]
|
|
struct StrCmpTemplate;
|
|
|
|
#[test]
|
|
fn str_cmp() {
|
|
let t = StrCmpTemplate;
|
|
assert_eq!(t.render().unwrap(), "AfooBotherCneitherD");
|
|
}
|