Generating Dynamic Content

Yaws has very nice support for generating dynamic content on the fly. We use embedded erlang code to generate the content. The Erlang code is separated from the HTML code by <erl> and </erl> markers. For example:


 out(Arg) ->
    {html, "Funky Stuff"}.



Is a very small example where we have a HTML document with embedded erlang code. A file which contains embedded erlang code must have the file suffix .yaws

The embedded erlang code can return the different values which will trigger the yaws webserver to do different things. We list some of the simple return values here:

It is often more convenient to return erlang terms which are then transformed to HTML instead of returning plain HTML in string form using the html tag

Using the ehtml return value, we can return deep structured erlang terms that correspond directly to HTML code. For example:

{table, [{bgcolor, "tan"}],
 {tr, [],
  [{td, [{width, "70%"}], {p, [{class, "foo"}], "Hi there"}}]}}

Corresponds to the following HTML code:

<table bgcolor="tan">
      <td width="70%">
        <p class="foo"> Hi there </p>

The embedded erlang code can also return a list of the above values. For example the following value

[{status, 303},
     [{header, ["Location: ",""]},
      {header, ["Set-Cookie: ","namn=ruler;"]}
 {html,"<html> Redirected to </html>"}

Can be returned if we want to issue a redirect and set a cookie at the same time.

All possible return values from the out/1 function are documented in the man page for yaws_api (5)

It can also be instructive to look at the actual source for the pages we are viewing at this very moment. Here are some of them

The argument

The out/1 function is supplied with a record argument. The definition of that record is automatically included in the embedded erlang code and the record definition is:

-record(arg, {
	  clisock,        %% the socket leading to the peer client
	  headers,        %% #headers{} record
	  req,            %% #http_request{} record
	  clidata,        %% The client data (as a binary in POST requests)
	  querydata,      %% Was the URL on the form of ....?query (GET reqs)
	  docroot,        %% where is the data
          fullpath,       %% absolute path to requested yaws file
	  server_path,    %% The normalized server path
	  pid,            %% pid of the yaws worker process
	  opaque          %% useful to pass static data


And some of the refered records are defined as:

-record(http_request, {method,

-record(headers, {
	  cookie = [],

Each chunk of erlang code will be compiled into a separate module. The module names are automatically generated. If we have functions inside the erlang chunks that we want to call from other chunks or modules, it is possible to explicitly name the modue that will be used as in:

   <erl module=foobar>
      out(A) ->
         io:format('This is the foobar module',[]).

      func() ->

Valid XHTML 1.0!