From f3a4c298ded3af62385d4747d91f7d11c8b2fd6e Mon Sep 17 00:00:00 2001 From: Thomas Lovegrove Date: Sat, 20 Apr 2019 02:39:24 +0100 Subject: [PATCH] Add implicit div class/id shorthand #172 (#173) * Add implicit div class/id shorthand * Add newline * Add short explanation and example of implicit div --- docs/content/basic-syntax.md | 4 ++-- maud/tests/basic_syntax.rs | 24 ++++++++++++++++++++++++ maud_macros/src/parse.rs | 6 ++++++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/docs/content/basic-syntax.md b/docs/content/basic-syntax.md index 03a67fe6..1c4c9803 100644 --- a/docs/content/basic-syntax.md +++ b/docs/content/basic-syntax.md @@ -129,11 +129,11 @@ html! { ## Classes and IDs `.foo` `#bar` -Add classes and IDs to an element using `.foo` and `#bar` syntax. You can chain multiple classes and IDs together, and mix and match them with other attributes: +Add classes and IDs to an element using `.foo` and `#bar` syntax. The tag will default to `div` if an element begins with a class or ID. You can chain multiple classes and IDs together, and mix and match them with other attributes: ```rust html! { - div.container#main { + .container#main { input.big.scary.bright-red type="button" value="Launch Party Cannon"; } } diff --git a/maud/tests/basic_syntax.rs b/maud/tests/basic_syntax.rs index e7312029..f81e6d8c 100644 --- a/maud/tests/basic_syntax.rs +++ b/maud/tests/basic_syntax.rs @@ -201,3 +201,27 @@ fn classes_attrs_ids_mixed_up() { let s = html!(p { "Hi, " span.name.here lang="en" #thing { "Lyra" } "!" }).into_string(); assert_eq!(s, r#"

Hi, Lyra!

"#); } + +#[test] +fn div_shorthand_class() { + let s = html!(.awesome-class {}).into_string(); + assert_eq!(s, r#"
"#); +} + +#[test] +fn div_shorthand_id() { + let s = html!(#unique-id {}).into_string(); + assert_eq!(s, r#"
"#); +} + +#[test] +fn div_shorthand_class_with_attrs() { + let s = html!(.awesome-class contenteditable? dir="rtl" #unique-id {}).into_string(); + assert_eq!(s, r#"
"#); +} + +#[test] +fn div_shorthand_id_with_attrs() { + let s = html!(#unique-id contenteditable? dir="rtl" .awesome-class {}).into_string(); + assert_eq!(s, r#"
"#); +} diff --git a/maud_macros/src/parse.rs b/maud_macros/src/parse.rs index 15a96de9..d83866b7 100644 --- a/maud_macros/src/parse.rs +++ b/maud_macros/src/parse.rs @@ -1,5 +1,6 @@ use proc_macro::{ Delimiter, + Ident, Literal, Spacing, Span, @@ -164,6 +165,11 @@ impl Parser { let name = self.try_namespaced_name().expect("identifier"); self.element(name)? }, + // Div element shorthand + TokenTree::Punct(ref punct) if punct.as_char() == '.' || punct.as_char() == '#' => { + let name = TokenTree::Ident(Ident::new("div", punct.span())); + self.element(name.into())? + }, // Splice TokenTree::Group(ref group) if group.delimiter() == Delimiter::Parenthesis => { self.advance();