在Rust中将HashMap转换为HTML的更好方法是什么?[关闭]

vnzz0bqm  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(48)

已关闭。此问题为opinion-based。目前不接受回答。
**要改进此问题吗?**更新此问题,以便editing this post可以使用事实和引文来回答。

27天前关闭。
Improve this question
我正在尝试用Rust将HashMap转换为HTML。转换为JSON是一个简单得多的主题。
我想到了这个:

fn convert_headers_to_html(headers: HashMap<String, Vec<String>>) -> String {
    let mut html_table_header = String::new();
    let mut html_table_content = String::new();

    html_table_header.push_str("<table>");
    html_table_header.push_str("<tr>");
    html_table_content.push_str("<tr>");
    for (k, v) in headers {
        //
        html_table_header.push_str("<th>");
        html_table_header.push_str(&k);
        html_table_header.push_str("</th>");

        html_table_content.push_str("<td>");
        html_table_content.push_str(&v.join(" "));
        html_table_content.push_str("</td>");
    }
    html_table_header.push_str("</tr>");
    html_table_content.push_str("</tr>");
    html_table_content.push_str("</table>");

    html_table_header.push_str(&html_table_content);
    html_table_header
}

字符串
只是感觉太冗长了。
还有更好的办法吗?

mwecs4sa

mwecs4sa1#

最好使用模板:

<table>
    <tr>
        {% for header in headers %}
        <th> {{ header }} </th>
        {% endfor %}
    </tr>
    <tr>
        {% for datum in data %}
        <td>{{ datum }}</td>
        {% endfor %}
    </tr>
</table>

字符串
然后使用模板:

use askama::Template;

#[derive(Template)]
#[template(path = "echo.html")]
struct EchoTemplate {
    headers: Vec<String>,
    data: Vec<String>,
}


fn convert_headers_to_html(headers: HashMap<String, Vec<String>>) -> String {
    let html_table = EchoTemplate {
        headers: headers.keys().cloned().collect(),
        data: headers.values().cloned().map(|v| v.join(" ")).collect(),
    };

    match html_table.render() {
        Ok(html) => html,
        _ => "Could not convert headers to html table".to_string(),
    }
}


效果很好。

相关问题