banksdev
banksdev

Reputation: 308

How to use rocket::response::Flash in a tera template

I am currently re-writing a web application built in python/flask that uses flashes as so:

{% with flashes = get_flashed_messages() %}
    {% if flashes %}
      <ul class=flashes>
      {% for message in flashes %}
        <li>{{ message }}
      {% endfor %}
      </ul>
    {% endif %}
{% endwith %}

I am new to both Rust and Rocket, and I can't find any documentation on how to handle flash cookies in a tera template. Is there a way to do this, or am I approaching the problem from the wrong angle?

Currently I have refactored it into something like what is seen below, but obviously the get_flashed_messages() part doesn't work.

{% set flashes = get_flashed_messages() %}
  {% if flashes %}
    <ul class=flashes>
    {% for message in flashes %}
      <li>{{ message }}
    {% endfor %}
    </ul>
{% endif %}

Upvotes: 1

Views: 547

Answers (1)

amishpanda
amishpanda

Reputation: 91

Here's the answer and source. The inspiration for my solution -> https://github.com/SergioBenitez/Rocket/issues/14#issuecomment-710698003

My working solution:

//some.html.tera file
...
{% if flash %}
    <p>{{flash}}</p>
{% endif %}
...

my function that consumes the Flash message

#[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)
}

Upvotes: 1

Related Questions