Last time we
started serving static files from the priv directory, supporting
validation caching, conditional requests, and compression. But since
static files are pretty boring, let’s populate our application’s page
with some dynamic content.
Dynamic content
Instead of the static “tweets” in the homepage, let’s replace them
with some content injected via Ajax.
First, remove all of the <li> elements from the <ul> in priv/www/index.html
(shown below):
To generate the dynamic content, we need to keep the base data
somewhere that we can fetch at runtime, we need to generate some
JSON for the browser, and we need to render that JSON into
HTML.
Let’s start by storing our tweets somewhere. Normally one would use a
real database and probably pull in Ecto to handle it. Since this is
just a tutorial, we’ll use ets
(Erlang Term Storage). Create
the ets table and populate it when the application starts up in the
start/2 function in tweeter.ex.
If you refresh your browser now, you won’t see anything because we
deleted the content without repopulating it. Instead, start up
iex and view the table using :ets.i(:tweets):
For some reason, the monotonic time returns a negative number on my
machine, but it should be sufficient to ensure uniqueness and
ordering. Now we should get that content into the browser, so it’s
time to make a new resource! Open up
lib/tweeter/resources/tweet_list.ex and paste in the boilerplate:
I’ve chosen a list this time for the resource state, because we
have a list of tweets to send to the browser. Let’s tell Webmachine
we want to serve JSON and how to render it:
Before we actually fetch the data from ETS, let’s hook up our new
resource and see that it’s working.
Now we should be able to bounce our server and see the JSON via curl:
Now let’s go back and fetch the tweets from ETS properly:
After bouncing our server, I get this response:
Woops! We got that timestamp but didn’t make it something that
makes sense in JSON. Let’s turn it into a numerical timestamp for
the client (microseconds since the epoch, basically).
Let’s try fetching our resource again:
Great! Now we can hook this up to our front-end with a little
JavaScript. We’re going to keep it simple by using jQuery instead
of a framework.
And hook up our JavaScript code at the bottom of index.html:
Refresh your browser and see the Ajax populate the tweet-list!
Up next
Now that we’ve got some dynamic content being displayed, in the
next installment we’ll allow the browser to post new tweets and insert them into
our ets table.