Question and answer system for the web

Worth Viewing

Perl's Template Toolkit [6] helps implementing the "View" part of the Catalyst MVC. It defines a template language, which is deliberately kept simple and allows users to define dynamic fields in static HTML. Although it supports simple programming logic, such as conditions or loops, it deliberately avoids the features of a full-fledged programming language because inexperienced developers tend to add more code in the view layer, instead of relying on a clear separation of the flow controller and the view. The command

script/quizshow
create.pl view TT TT

using the included quizshow_create.pl Catalyst helper script adds the lib/QuizShow/View/TT.pm module to the directory tree created previously. The first TT represents the name of the module created here (TT.pm); the second one ensures that the latter is a class derived from the Template Toolkit View. Alternatively, Catalyst supports the Mason and HTML::Template toolkits.

Catalyst also tells the TT.pm module to  se the Template Toolkit processor to handle files ending with .tt before the web server delivers them. Figure 6 shows the quiz.tt template, which must reside in the root directory of the newly created Catalyst project.

First, the [% IF %] condition written in Template Toolkit syntax checks to see whether more questions exist. If not, the browser displays the final score, otherwise it uses the Template variables score_ok and score_nok to display the current score and the number of questions left.

The template then outputs the current question and uses the FOREACH loop to iterate through the randomly ordered answers and present them as clickable radio buttons.

The Submit button sends the web form to the web server at the original URL because the HTML doesn't specify a form URL.

Control the Flow

To define the application's control flow, you also need a Quiz.pm Controller:

script/quizshow_create.pl controller Quiz

This command line creates the lib/QuizShow/Controller/Quiz.pm file, to which you need to add the code shown in Listing 1, Ctrl-Quiz.pm.

Listing 1

Ctrl-Quiz.pm

 

Quiz.pm defines the quiz() method, which has the :Global attribute. This allows Catalyst to catch any requests below the http://localhost:3000/quiz URL and pass any subsequent paths in to the application as the @args parameter. For example, if the user adds /quiz/reset to the URL, Catalyst calls the quiz() method and sets the first element of @args to reset.

On /reset, the quiz() resets the session data to zero and asks the browser to redirect to the application start page. This changes the URL displayed in the browser from /quiz/reset to /quiz; the controller sets the counter for right and wrong answers to 0, and a new quiz can begin.

The Catalyst object's uri_for() method generates absolute URLs from URLs entered relative to the application root, allowing the browser to redirect to them. The redirect() method itself only sets an http header, but does not interrupt the control flow; this is what makes the $c->detach() that follows in Line 24 so important.

Break the Flow

This causes Catalyst to finish processing the request. Incidentally, this is a practical method of stopping the control flow, even if you are in the middle of a nested loop construction. The $c variable points to the Catalyst system's context object; it is added to the controller's methods with the call and is useful for retrieving almost anything from the depths of the Catalyst system.

The Catalyst object's $c's session() method reveals the session hash, which is made persistent by cookies and server-side storage, including the entries next_question (index of the next question to be asked in the YAML array), score_ok (the number of questions answered correctly), score_nok (the number of questions answered incorrectly), total (total number of questions), and correct_answer to let the server know which of the randomly ordered answers is the right one for the question just posed.

Catalyst uses

$c->req->param("answer")

in line 28 to retrieve the answer form parameter provided by the browser from the request object. This number is equivalent to the number 1, 2, or 3 for the radio button clicked by the user to select an answer. If the value matches the value stored in the session hash on the server before the web page was served up, the response was correct, and the controller increments the score_ok session variable.

In line 43 the controller defines quiz.tt as the template and then stores variable values in the template stash. If the controller sets $c->stash->{score _ok}, the template processor will replace the template entry [% score_ok %] with the value determined in the controller.

Stash variables can be arbitrarily nested data structures; for example, the stash entry answers contains a pointer to an array whose elements in turn are pointers to hashes, which contain the text and number of an answer indexed by the text and num keys.

The quiz.tt template iterates over this array to display all possible answers. It assigns an alias named answer to the currently processed element and then uses [% answer.text %] and [% answer.num %] to access the underlying hash entries – that's a very practical template toolkit feature that saves a lot typing.

Lines 50 to 52 create a data structure from the answer array extracted from the YAML file. The array assigns a correct tag to the first entry, and incorrect to all others. To display the answers in random order, the while loop in line 57 picks up a random element from this array of arrays. If this is the answer tagged as correct, the controller remembers the number for the session hash later on.

Lines 60 to 62 generate a hash with the text and num entries from the answer and pushes it to the end of the answers stash. The quiz.tt template picks up the data and dynamically creates the HTML output.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

comments powered by Disqus
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters

Support Our Work

Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.

Learn More

News