问题描述
我目前正在重新编写一个用 python/flask 构建的 Web 应用程序,它使用 Flash:
{% with flashes = get_flashed_messages() %}
{% if flashes %}
<ul class=flashes>
{% for message in flashes %}
<li>{{ message }}
{% endfor %}
</ul>
{% endif %}
{% endwith %}
我是 Rust 和 Rocket 的新手,我找不到任何关于如何在 tera 模板中处理 flash cookie 的文档。有没有办法做到这一点,还是我从错误的角度处理问题?
目前我已将其重构为如下所示的内容,但显然 get_flashed_messages()
部分不起作用。
{% set flashes = get_flashed_messages() %}
{% if flashes %}
<ul class=flashes>
{% for message in flashes %}
<li>{{ message }}
{% endfor %}
</ul>
{% endif %}
解决方法
这是答案和来源。 我的解决方案的灵感 -> https://github.com/SergioBenitez/Rocket/issues/14#issuecomment-710698003
我的工作解决方案:
//some.html.tera file
...
{% if flash %}
<p>{{flash}}</p>
{% endif %}
...
我使用 Flash 消息的函数
#[get("/signup")]
fn signup_page(flash: Option<FlashMessage>) -> Template {
let mut context: HashMap<&str,Option<String>> = HashMap::new();
context.insert("flash",flash.map(|msg| format!("{}! {}",msg.name(),msg.msg())));
Template::render("signup",&context)
}