Issue
I have lots of varyingly wide sets of data, I need to insert into tables. Yew is overkill, just looking for kiss. As in
//format!("<tr><td>{e1}</td><td>{e2}</td></tr>") – no good, might be exprs
format!("<tr><td>{}</td><td>{}</td></tr>", e1, e2)
I want to simplify this for any number of columns
macro_rules! tr {
($($td:expr),*) => {
format!(concat!("<tr>", $("<td>{}</td>"),* "</tr>"), $($td),*)
}
}
tr!(e1, e2)
gives error: attempted to repeat an expression containing no syntax variables matched as repeating at this depth
So I tried an artificial code block, just to give it the variable in the 1st repeat
macro_rules! tr {
($($td:expr),*) => {
format!(concat!("<tr>", $({ $td; "<td>{}</td>" }),* "</tr>"), $($td),*)
}
}
gives error: expected token: ,
What would the right syntax be?
Solution
When you need to repeat some expression the same times as a metavariable but without including it in the expression, there is a trick: define an internal macro arm/another internal macro that takes the metavariable and produces the constant expression. This way, you can "use" the metavariable in the reptition without actually including it:
macro_rules! tr {
(@trick $td:expr) => { "<td>{}</td>" };
($($td:expr),*) => {
format!(concat!("<tr>", $(tr!(@trick $td),)* "</tr>"), $($td),*)
}
}
On nightly, there is an easier way: using the ${ignore(...)}
modifier that is meant exactly for that:
#![feature(macro_metavar_expr)]
macro_rules! tr {
($($td:expr),*) => {
format!(concat!("<tr>", $("<td>{}</td>", ${ignore(td)})* "</tr>"), $($td),*)
}
}
Answered By - Chayim Friedman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.