Skip to content

Commit

Permalink
Merge pull request #28 from Nemo157/class-shorthand
Browse files Browse the repository at this point in the history
Add a shorthand syntax to define element classes
  • Loading branch information
lambda-fairy committed Feb 8, 2016
2 parents 0440f5c + da86d54 commit 6b14129
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
21 changes: 21 additions & 0 deletions maud_macros/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,7 @@ impl<'cx, 'i> Parser<'cx, 'i> {
parse_error!(self, sp, "unexpected element, you silly bumpkin");
}
self.render.element_open_start(name);
try!(self.class_shorthand());
try!(self.attrs());
self.render.element_open_end();
if let [slash!(), ..] = self.input {
Expand All @@ -375,6 +376,26 @@ impl<'cx, 'i> Parser<'cx, 'i> {
Ok(())
}

/// Parses and renders the attributes of an element.
fn class_shorthand(&mut self) -> PResult<()> {
let mut classes = Vec::new();
loop {
match self.input {
[dot!(), ident!(_, _), ..] => {
self.shift(1);
classes.push(try!(self.name()));
},
_ => break,
}
}
if !classes.is_empty() {
self.render.attribute_start("class");
self.render.string(&classes.join(" "));
self.render.attribute_end();
}
Ok(())
}

/// Parses and renders the attributes of an element.
fn attrs(&mut self) -> PResult<()> {
loop {
Expand Down
35 changes: 35 additions & 0 deletions maud_macros/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -330,3 +330,38 @@ fn splice_with_path() {
html!(s, $inner::name()).unwrap();
assert_eq!(s, "Maud");
}

#[test]
fn class_shorthand() {
let mut s = String::new();
html!(s, p { "Hi, " span.name { "Lyra" } "!" }).unwrap();
assert_eq!(s, "<p>Hi, <span class=\"name\">Lyra</span>!</p>");
}

#[test]
fn class_shorthand_with_space() {
let mut s = String::new();
html!(s, p { "Hi, " span .name { "Lyra" } "!" }).unwrap();
assert_eq!(s, "<p>Hi, <span class=\"name\">Lyra</span>!</p>");
}

#[test]
fn classes_shorthand() {
let mut s = String::new();
html!(s, p { "Hi, " span.name.here { "Lyra" } "!" }).unwrap();
assert_eq!(s, "<p>Hi, <span class=\"name here\">Lyra</span>!</p>");
}

#[test]
fn classes_shorthand_with_space() {
let mut s = String::new();
html!(s, p { "Hi, " span .name .here { "Lyra" } "!" }).unwrap();
assert_eq!(s, "<p>Hi, <span class=\"name here\">Lyra</span>!</p>");
}

#[test]
fn classes_shorthand_with_attrs() {
let mut s = String::new();
html!(s, p { "Hi, " span.name.here id="thing" { "Lyra" } "!" }).unwrap();
assert_eq!(s, "<p>Hi, <span class=\"name here\" id=\"thing\">Lyra</span>!</p>");
}

0 comments on commit 6b14129

Please sign in to comment.