Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a <tr><td> macro?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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),*)
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading