Skip to content
This repository was archived by the owner on Nov 7, 2018. It is now read-only.

Snippets

davebryson edited this page Sep 13, 2010 · 4 revisions

Using Flash Messages

If you know Rails, Flash within BeepBeep works very similar. Flash are messages you can pass between requests. The messages you pass in BeepBeep can be any Erlang term and they are internally wrapped in a List, so you can have pass 1 or more messages at a time. The flash only last through 1 request or redirect. After that it is removed. The BeepBeep API places all flash messages automatically in the data passed to your template with the key: flash. Here’s a simple example from the Blog application included with the source code:

‘home_controller.erl’


handle_request("create",[]) -> Title = beepbeep_args:get_param("post_title",Env), Body = beepbeep_args:get_param("post_body",Env), %% Example of validation. Require a Title if

Title =:= undefined orelse length(Title) =:= 0 →
% Blank
%
Set flash message for the template
beepbeep_args:flash({notice,“Title Required!”},Env),
{redirect,“/home/new”};
true →
%% Set flash message for the template
beepbeep_args:flash({notice,“Post Created!”},Env),
blog_database:insert(Title,Body),
{redirect,“/”}
end.


On a create we validate that a Title is entered. If the Title is missing we set the Flash message and redirect to ‘new’:


...

beepbeep_args:flash({notice,"Title Required!"},Env),
{redirect,"/home/new"};

Here’s the template snippet in ‘new.html’


{% extends "../base.html" %}
{% block content %}

{% include "flash.html" %}

<h2>Add a Post</h2> 
<form action="/home/create" method="post">
  Title:<br/> 
  <input type="text" name="post_title" value="" size="40"/>
  <br/>
  <textarea name="post_body" value="" rows="10" cols="40"></textarea>
  <br/>
  <input type="submit" name="submit" value="Save"/>&nbsp;|&nbsp;<a href="/">Cancel</a>
</form>

{% endblock %}

The part we’re interested in is the ‘{ % include flash.html %}’ which is a reusable template for displaying the flash message. Here’s ‘flash.html’:


{% if flash %}
  {% for k,message in flash %}
    <p>{{ message }}</p>
  {% endfor %}
{% endif %}

Of course you are free to style ‘flash.html’ anyway you choose. So they main thing to know about Flash is to use call:


beepbeep_args:flash({MYKEY,"MYMESSAGE"},Env),

in your controller. And style the message in the template using the key flash

Clone this wiki locally