980 lines
No EOL
39 KiB
HTML
980 lines
No EOL
39 KiB
HTML
<?xml version="1.0" encoding="utf-8"?>
|
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
|
|
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
|
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr" xml:lang="fr">
|
|
<head>
|
|
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
|
|
|
|
|
<meta name="keywords" content="yesod, haskell, programming, web">
|
|
|
|
<link rel="shortcut icon" type="image/x-icon" href="/Scratch/img/favicon.ico" />
|
|
<link rel="stylesheet" type="text/css" href="/Scratch/assets/css/main.css" />
|
|
<link rel="stylesheet" type="text/css" href="/Scratch/css/solarized.css" />
|
|
<link rel="stylesheet" type="text/css" href="/Scratch/css/idc.css" />
|
|
<link href='http://fonts.googleapis.com/css?family=Inconsolata' rel='stylesheet' type='text/css'>
|
|
<link rel="alternate" type="application/rss+xml" title="RSS" href="http://feeds.feedburner.com/yannespositocomen"/>
|
|
|
|
<link rel="alternate" lang="fr" xml:lang="fr" title="Site en Haskell" type="text/html" hreflang="fr" href="/Scratch/fr/blog/Yesod-tutorial-for-newbies/" />
|
|
<link rel="alternate" lang="en" xml:lang="en" title="Haskell web programming" type="text/html" hreflang="en" href="/Scratch/en/blog/Yesod-tutorial-for-newbies/" />
|
|
<script type="text/javascript" src="/Scratch/js/jquery-1.3.1.min.js"></script>
|
|
<script type="text/javascript" src="/Scratch/js/jquery.cookie.js"></script>
|
|
<script type="text/javascript" src="/Scratch/js/index.js"></script>
|
|
<script type="text/javascript" src="/Scratch/js/highlight/highlight.pack.js"></script>
|
|
<script type="text/javascript" src="/Scratch/js/article.js"></script>
|
|
<!--[if lt IE 9]>
|
|
<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js"></script>
|
|
<![endif]-->
|
|
<title>Haskell web programming</title>
|
|
</head>
|
|
<body lang="en" class="article">
|
|
<script type="text/javascript">// <![CDATA[
|
|
document.write('<div id="blackpage"><img src="/Scratch/img/loading.gif" alt="loading..."/></div>');
|
|
// ]]>
|
|
</script>
|
|
|
|
<div id="content">
|
|
|
|
<div id="choix">
|
|
<div class="return"><a href="#entete">↓ Menu ↓</a></div>
|
|
<div id="choixlang">
|
|
<a href="/Scratch/fr/blog/Yesod-tutorial-for-newbies/" onclick="setLanguage('fr')">en Français</a>
|
|
</div>
|
|
<div class="flush"></div>
|
|
</div>
|
|
<div id="titre">
|
|
<h1>
|
|
Haskell web programming
|
|
</h1>
|
|
|
|
<h2>
|
|
A Yesod tutorial
|
|
</h2>
|
|
|
|
</div>
|
|
<div class="flush"></div>
|
|
|
|
|
|
|
|
|
|
|
|
<div class="flush"></div>
|
|
<div id="afterheader">
|
|
<div class="corps">
|
|
<p><img alt="Neo Flying at warp speed" src="/Scratch/img/blog/Yesod-tutorial-for-newbies/flying_neo.jpg" /></p>
|
|
|
|
|
|
<div class="intro">
|
|
|
|
|
|
<p><em>update</em>: updated for yesod 0.10</p>
|
|
|
|
<p><span class="sc"><abbr title="Too long; didn't read">tl;dr</abbr>: </span> A simple yesod tutorial.
|
|
Yesod is a Haskell web framework.
|
|
You shouldn’t need to know Haskell. </p>
|
|
|
|
<blockquote>
|
|
<center><span class="sc"><b>Table of content</b></span></center>
|
|
|
|
<ul id="markdown-toc">
|
|
<li><a href="#before-the-real-start">Before the real start</a> <ul>
|
|
<li><a href="#install">Install</a></li>
|
|
<li><a href="#initialize">Initialize</a></li>
|
|
<li><a href="#configure-git">Configure git</a></li>
|
|
<li><a href="#some-last-minute-words">Some last minute words</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#echo">Echo</a> <ul>
|
|
<li><a href="#bulletproof">Bulletproof?</a></li>
|
|
<li><a href="#cleaning-up">Cleaning up</a> <ul>
|
|
<li><a href="#use-a-better-span-classsccssspan">Use a better <span class="sc">css</span></a></li>
|
|
<li><a href="#separate-handlers">Separate Handlers</a></li>
|
|
<li><a href="#datatext"><code>Data.Text</code></a></li>
|
|
<li><a href="#use-templates">Use templates</a></li>
|
|
</ul>
|
|
</li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#mirror">Mirror</a></li>
|
|
<li><a href="#a-blog">A Blog</a></li>
|
|
<li><a href="#conclusion">Conclusion</a></li>
|
|
</ul>
|
|
</blockquote>
|
|
|
|
|
|
</div>
|
|
|
|
|
|
<p>Why Haskell?</p>
|
|
|
|
<p><img alt="Impressive Haskell Benchmark" src="/Scratch/img/blog/Yesod-tutorial-for-newbies/haskell-benchmark.png" /></p>
|
|
|
|
<p>Its efficiency (see <a href="http://snapframework.com/blog/2010/11/17/snap-0.3-benchmarks">Snap Benchmark</a> <em class="pala">&</em>
|
|
<a href="http://www.yesodweb.com/blog/2011/03/preliminary-warp-cross-language-benchmarks">Warp Benchmark</a><sup id="fnref:benchmarkdigression"><a href="#fn:benchmarkdigression" rel="footnote">1</a></sup>).
|
|
Haskell is an order of magnitude faster than interpreted languages
|
|
like <a href="http://shootout.alioth.debian.org/u64q/benchmark.php?test=all&lang=ghc&lang2=yarv">Ruby</a> and <a href="http://shootout.alioth.debian.org/u64q/benchmark.php?test=all&lang=ghc&lang2=python3">Python</a><sup id="fnref:speeddigression"><a href="#fn:speeddigression" rel="footnote">2</a></sup>.</p>
|
|
|
|
<p>Haskell is a high level language and make it harder to shoot you in the foot
|
|
than <code>C</code>, <code>C++</code> or <code>Java</code> for example.
|
|
One of the best property of Haskell being:</p>
|
|
|
|
<blockquote>
|
|
<p>“If your program compile it will be
|
|
very close to what the programmer intended”.</p>
|
|
</blockquote>
|
|
|
|
<p>Haskell web frameworks handle parallel tasks perfectly.
|
|
For example even better than node.js<sup id="fnref:nodejstroll"><a href="#fn:nodejstroll" rel="footnote">3</a></sup>.</p>
|
|
|
|
<p><img alt="Thousands of Agent Smith" src="/Scratch/img/blog/Yesod-tutorial-for-newbies/thousands_smiths.jpg" class=" left" /></p>
|
|
|
|
<p>From the pure technical point of view,
|
|
Haskell seems to be the perfect web development tool.
|
|
Weaknesses of Haskell certainly won’t be technical:</p>
|
|
|
|
<ul>
|
|
<li>Hard to grasp Haskell</li>
|
|
<li>Hard to find a Haskell programmer</li>
|
|
<li>The Haskell community is smaller than the community for <code>/.*/</code> </li>
|
|
<li>There is no <a href="http://heroku.com">heroku</a> for Haskell (even if <a href="http://www.yesodweb.com/blog/2011/07/haskell-on-heroku">Greg Weber did it</a>, it was more a workaround).</li>
|
|
</ul>
|
|
|
|
<p>I won’t say these are not important drawbacks.
|
|
But, with Haskell your web application will have both properties
|
|
to absorb an impressive number of parallel request securely
|
|
and to adapt to change.</p>
|
|
|
|
<p>Actually there are three main Haskell web frameworks:</p>
|
|
|
|
<ol>
|
|
<li><a href="http://happstack.com">Happstack</a></li>
|
|
<li><a href="http://snapframework.com">Snap</a></li>
|
|
<li><a href="http://yesodweb.com">Yesod</a></li>
|
|
</ol>
|
|
|
|
<p>I don’t think there is a real winner between these three framework.
|
|
The choice I made for yesod is highly subjective.
|
|
I just lurked a bit and tried some tutorials.
|
|
I had the feeling yesod make a better job at helping newcomers.
|
|
Furthermore, apparently the yesod team seems the most active.
|
|
Of course I might be wrong since it is a matter of feeling.</p>
|
|
|
|
<p><img alt="1. Draw some circles. 2. Draw the rest of the fucking owl" src="/Scratch/img/blog/Yesod-tutorial-for-newbies/owl_draw.png" /></p>
|
|
|
|
<p>Why did I write this article?
|
|
The yesod documentation and particularly the book are excellent.
|
|
But I missed an intermediate tutorial.
|
|
This tutorial won’t explain all details.
|
|
I tried to give a step by step of how to start from a five minute tutorial
|
|
to an almost production ready architecture.
|
|
Furthermore explaining something to others is a great way to learn.
|
|
If you are used to Haskell and Yesod, this tutorial won’t learn you much.
|
|
If you are completely new to Haskell and Yesod it might hopefully helps you.
|
|
Also if you find yourself too confused by the syntax, it might helps to read this
|
|
<a href="http://blog.ezyang.com/2011/11/how-to-read-haskell/">article</a></p>
|
|
|
|
<p>During this tutorial you’ll install, initialize and configure your first yesod project.
|
|
Then there is a very minimal 5 minutes yesod tutorial to heat up and verify the awesomeness of yesod.
|
|
Then we will clean up the 5 minutes tutorial to use some “best practices”.
|
|
Finally there will be a more standard real world example; a minimal blog system.</p>
|
|
|
|
<h2 id="before-the-real-start">Before the real start</h2>
|
|
|
|
<h3 id="install">Install</h3>
|
|
|
|
<p>The recommended way to install <a href="http://www.haskell.org">Haskell</a>
|
|
is to download the <a href="http://www.haskell.org/platform">Haskell Platform</a>.</p>
|
|
|
|
<p>Once done, you need to install yesod.
|
|
Open a terminal session and do:</p>
|
|
|
|
<pre><code class="zsh">~ cabal update
|
|
~ cabal install yesod cabal-dev
|
|
</code></pre>
|
|
|
|
<p>There are few steps but it should take some time to finish.</p>
|
|
|
|
<h3 id="initialize">Initialize</h3>
|
|
|
|
<p>You are now ready to initialize your first yesod project.
|
|
Open a terminal and type:</p>
|
|
|
|
<pre><code class="zsh">~ yesod init
|
|
</code></pre>
|
|
|
|
<p>Enter your name, choose <code>yosog</code> for the project name and enter <code>Yosog</code> for the name of the Foundation.
|
|
Finally choose <code>sqlite</code>.
|
|
Now, start the development cycle:</p>
|
|
|
|
<pre><code class="zsh">~ cd yosog
|
|
~ cabal-dev install && yesod --dev devel
|
|
</code></pre>
|
|
|
|
<p>This will compile the entire project. Be patient it could take a while the first time.
|
|
Once finished a server is launched and you could visit it by clicking this link:</p>
|
|
|
|
<p><a href="http://localhost:3000"><code>http://localhost:3000</code></a></p>
|
|
|
|
<p>Congratulation! Yesod works!</p>
|
|
|
|
<blockquote>
|
|
|
|
Note: if something is messed up use the following command line inside the project directory.
|
|
|
|
|
|
|
|
<pre><code class="zsh">\rm -rf dist/* ; cabal-dev install && yesod --dev devel
|
|
</code></pre>
|
|
|
|
|
|
|
|
</blockquote>
|
|
|
|
<p>Until the end of the tutorial, use another terminal and let this one open
|
|
in a corner to see what occurs.</p>
|
|
|
|
<h3 id="configure-git">Configure git</h3>
|
|
|
|
<blockquote>
|
|
<p>Of course this step is not mandatory for the tutorial
|
|
but it is a good practice.</p>
|
|
</blockquote>
|
|
|
|
<p>Copy this <code>.gitignore</code> file into the <code>yosog</code> folder.</p>
|
|
|
|
<div class="codefile"><a href="/Scratch/en/blog/Yesod-tutorial-for-newbies/code/.gitignore">➥ .gitignore</a></div>
|
|
|
|
<pre><code class="zsh">cabal-dev
|
|
dist
|
|
.static-cache
|
|
static/tmp
|
|
*.sqlite3
|
|
</code></pre>
|
|
|
|
<p>Then initialize your git repository:</p>
|
|
|
|
<pre><code class="zsh">~ git init .
|
|
~ git add .
|
|
~ git commit -a -m "Initial yesod commit"
|
|
</code></pre>
|
|
|
|
<p>We are almost ready to start.</p>
|
|
|
|
<h3 id="some-last-minute-words">Some last minute words</h3>
|
|
|
|
<p>Up until here, we have a directory containing a bunch of files
|
|
and a local web server listening the port 3000.
|
|
If we modify a file inside this directory, yesod should try
|
|
to recompile as fast as possible the site.
|
|
Instead of explaining the role of every file,
|
|
let’s focus only on the important files/directories for this tutorial:</p>
|
|
|
|
<ol>
|
|
<li><code>config/routes</code></li>
|
|
<li><code>Handler/</code></li>
|
|
<li><code>templates/</code></li>
|
|
<li><code>config/models</code></li>
|
|
</ol>
|
|
|
|
<p>Obviously:</p>
|
|
|
|
<table>
|
|
<tbody>
|
|
<tr>
|
|
<td><code>config/routes</code></td>
|
|
<td>is where you’ll configure the map <span class="sc">url</span> → Code.</td>
|
|
</tr>
|
|
<tr>
|
|
<td><code>Handler/</code></td>
|
|
<td>contains the files that will contain the code called when a <span class="sc">url</span> is accessed.</td>
|
|
</tr>
|
|
<tr>
|
|
<td><code>templates/</code></td>
|
|
<td>contains <span class="sc">html</span>, js and <span class="sc">css</span> templates.</td>
|
|
</tr>
|
|
<tr>
|
|
<td><code>config/models</code></td>
|
|
<td>is where you’ll configure the persistent objects (database tables).</td>
|
|
</tr>
|
|
</tbody>
|
|
</table>
|
|
|
|
<p>During this tutorial we’ll modify other files as well,
|
|
but we won’t explore them in detail.</p>
|
|
|
|
<p>Also note, shell commands are executed in the root directory of your project instead specified otherwise.</p>
|
|
|
|
<p>We are now ready to start!</p>
|
|
|
|
<h2 id="echo">Echo</h2>
|
|
|
|
<p>To verify the quality of the security of the yesod framework,
|
|
let’s make a minimal echo application.</p>
|
|
|
|
<blockquote>
|
|
<p>Goal:</p>
|
|
|
|
<p>Make a server that when accessed <code>/echo/[some text]</code> should return a web page containing “some text” inside an <code>h1</code> bloc.</p>
|
|
</blockquote>
|
|
|
|
<p>In a first time, we must declare the <span class="sc">url</span> of the form <code>/echo/...</code> are meaningful.
|
|
Let’s take a look at the file <code>config/routes</code>:</p>
|
|
|
|
<pre>
|
|
/static StaticR Static getStatic
|
|
/auth AuthR Auth getAuth
|
|
|
|
/favicon.ico FaviconR GET
|
|
/robots.txt RobotsR GET
|
|
|
|
/ HomeR GET
|
|
</pre>
|
|
|
|
<p>We want to add a route of the form <code>/echo/[anything]</code> somehow and do some action with this.
|
|
Add the following:</p>
|
|
|
|
<pre>
|
|
/echo/#String EchoR GET
|
|
</pre>
|
|
|
|
<p>This line contains three elements: the <span class="sc">url</span> pattern, a handler name, an <span class="sc">http</span> method.
|
|
I am not particularly fan of the big R notation but this is the standard convention.</p>
|
|
|
|
<p>If you save <code>config/routes</code>, you should see your terminal in which you launched <code>yesod devel</code> activate and certainly displaying an error message.</p>
|
|
|
|
<pre>
|
|
Application.hs:31:1: Not in scope: `getEchoR'
|
|
</pre>
|
|
|
|
<p>Why? Simply because we didn’t written the code for the handler <code>EchoR</code>.
|
|
Edit the file <code>Handler/Home.hs</code> and append this:</p>
|
|
|
|
<pre><code class="haskell">getEchoR :: String -> Handler RepHtml
|
|
getEchoR theText = do
|
|
defaultLayout $ do
|
|
[whamlet|<h1>#{theText}|]
|
|
</code></pre>
|
|
|
|
<p>Don’t worry if you find all of this a bit cryptic.
|
|
In short it just declare a function named <code>getEchoR</code> with one argument (<code>theText</code>) of type String.
|
|
When this function is called, it return a <code>Handler RepHtml</code> whatever it is.
|
|
But mainly this will encapsulate our expected result inside an <span class="sc">html</span> text.</p>
|
|
|
|
<p>After saving the file, you should see yesod recompile the application.
|
|
When the compilation is finished you’ll see the message: <code>Starting devel application</code>.</p>
|
|
|
|
<p>Now you can visit: <a href="http://localhost:3000/echo/Yesod%20rocks!"><code>http://localhost:3000/echo/Yesod%20rocks!</code></a></p>
|
|
|
|
<p>TADA! It works! </p>
|
|
|
|
<h3 id="bulletproof">Bulletproof?</h3>
|
|
|
|
<p><img alt="Neo stops a myriad of bullets" src="/Scratch/img/blog/Yesod-tutorial-for-newbies/neo_bullet_proof.jpg" /></p>
|
|
|
|
<p>Even this extremely minimal web application has some impressive properties.
|
|
For exemple, imagine an attacker entering this <span class="sc">url</span>:</p>
|
|
|
|
<p><a href="http://localhost:3000/echo/<a>I'm <script>alert("Bad!");"><code>http://localhost:3000/echo/<a>I'm <script>alert("Bad!");</code></a></p>
|
|
|
|
<p>The special characters are protected for us.
|
|
A malicious user could not hide some bad script inside.</p>
|
|
|
|
<p>This behavior is a direct consequence of <em>type safety</em>.
|
|
The <span class="sc">url</span> string is put inside a <span class="sc">url</span> type.
|
|
Then the interesting part in the <span class="sc">url</span> is put inside a String type.
|
|
To pass from <span class="sc">url</span> type to String type some transformation are made.
|
|
For example, replace all “<code>%20</code>” by space characters.
|
|
Then to show the String inside an <span class="sc">html</span> document, the string is put inside an <span class="sc">html</span> type.
|
|
Some transformations occurs like replace “<code><</code>” by “<code>&lt;</code>”.
|
|
Thanks to yesod, this tedious job is done for us.</p>
|
|
|
|
<pre><code class="zsh">"http://localhost:3000/echo/some%20text<a>" :: URL
|
|
↓
|
|
"some text<a>" :: String
|
|
↓
|
|
"some text <a>" :: Html
|
|
</code></pre>
|
|
|
|
<p>Yesod is not only fast, it helps us to remain secure.
|
|
It protects us from many common errors in other paradigms.
|
|
Yes, I am looking at you PHP!</p>
|
|
|
|
<h3 id="cleaning-up">Cleaning up</h3>
|
|
|
|
<p>Even this very minimal example should be enhanced.
|
|
We will clean up many details:</p>
|
|
|
|
<ul>
|
|
<li>Use a general <span class="sc">css</span> (cleaner than the empty by default)</li>
|
|
<li>Dispatch handler code into different files</li>
|
|
<li>Use <code>Data.Text</code> instead of <code>String</code></li>
|
|
<li>Put our “views”<sup id="fnref:explainviewwidget"><a href="#fn:explainviewwidget" rel="footnote">4</a></sup> inside the <code>template</code> directory</li>
|
|
</ul>
|
|
|
|
<h4 id="use-a-better-span-classsccssspan">Use a better <span class="sc">css</span></h4>
|
|
|
|
<p>It is nice to note, the default template is based on <span class="sc">html5</span> boilerplate.
|
|
Let’s change the default <span class="sc">css</span>.
|
|
Add a file named <code>default-layout.lucius</code> inside the <code>templates/</code> directory containing:</p>
|
|
|
|
<div class="codefile"><a href="/Scratch/en/blog/Yesod-tutorial-for-newbies/code/default-layout.lucius">➥ default-layout.lucius</a></div>
|
|
|
|
<pre><code class="css">body {
|
|
font-family: Helvetica, sans-serif;
|
|
font-size: 18px; }
|
|
#main {
|
|
padding: 1em;
|
|
border: #CCC solid 2px;
|
|
border-radius: 5px;
|
|
margin: 1em;
|
|
width: 37em;
|
|
margin: 1em auto;
|
|
background: #F2F2F2;
|
|
line-height: 1.5em;
|
|
color: #333; }
|
|
.required { margin: 1em 0; }
|
|
.optional { margin: 1em 0; }
|
|
label { width: 8em; display: inline-block; }
|
|
input, textarea { background: #FAFAFA}
|
|
textarea { width: 27em; height: 9em;}
|
|
ul { list-style: square; }
|
|
a { color: #A56; }
|
|
a:hover { color: #C58; }
|
|
a:active { color: #C58; }
|
|
a:visited { color: #943; }
|
|
</code></pre>
|
|
|
|
<p>Personally I would prefer if such a minimal <span class="sc">css</span> was put with the scaffolding tool.
|
|
I am sure somebody already made such a minimal <span class="sc">css</span> which give the impression
|
|
the browser handle correctly <span class="sc">html</span> without any style applied to it.
|
|
But I digress.</p>
|
|
|
|
<h4 id="separate-handlers">Separate Handlers</h4>
|
|
|
|
<p>Generally you don’t want to have all your code inside a unique file.
|
|
This is why we will separate our handlers.
|
|
In a first time create a new file <code>Handler/Echo.hs</code> containing:</p>
|
|
|
|
<pre><code class="haskell">module Handler.Echo where
|
|
|
|
import Import
|
|
|
|
getEchoR :: String -> Handler RepHtml
|
|
getEchoR theText = do
|
|
defaultLayout $ do
|
|
[whamlet|<h1>#{theText}|]
|
|
</code></pre>
|
|
|
|
<p>Do not forget to remove the getEchoR function inside <code>Handler/Home.hs</code>.</p>
|
|
|
|
<p>We must declare this new file into<code>yosog.cabal</code>.
|
|
Just after <code>Handler.Home</code>, add:</p>
|
|
|
|
<pre>
|
|
Handler.Echo
|
|
</pre>
|
|
|
|
<p>We must also declare this new Handler module inside <code>Application.hs</code>.
|
|
Just after the “<code>import Handler.Home</code>”, add:</p>
|
|
|
|
<pre><code class="haskell">import Handler.Echo
|
|
</code></pre>
|
|
|
|
<p>This is it. </p>
|
|
|
|
<p><small><em>ps:</em> I am sure not so far in the future we could simply write
|
|
<code>yesod add-handler Echo</code> to declare it and create a new handler file.</small></p>
|
|
|
|
<h4 id="datatext"><code>Data.Text</code></h4>
|
|
|
|
<p>It is a good practice to use <code>Data.Text</code> instead of <code>String</code>.</p>
|
|
|
|
<p>To declare it, add this import directive to <code>Foundation.hs</code> (just after the last one):</p>
|
|
|
|
<pre><code class="diff">import Data.Text
|
|
</code></pre>
|
|
|
|
<p>We have to modify <code>config/routes</code> and our handler accordingly.
|
|
Replace <code>#String</code> by <code>#Text</code> in <code>config/routes</code>:</p>
|
|
|
|
<pre>
|
|
/echo/#Text EchoR GET
|
|
</pre>
|
|
|
|
<p>And do the same in <code>Handler/Echo.hs</code>:</p>
|
|
|
|
<div class="codefile"><a href="/Scratch/en/blog/Yesod-tutorial-for-newbies/code/Echo.hs">➥ Echo.hs</a></div>
|
|
|
|
<pre><code class="haskell">module Handler.Echo where
|
|
|
|
import Import
|
|
|
|
getEchoR :: Text -> Handler RepHtml
|
|
getEchoR theText = do
|
|
defaultLayout $ do
|
|
[whamlet|<h1>#{theText}|]
|
|
</code></pre>
|
|
|
|
<h4 id="use-templates">Use templates</h4>
|
|
|
|
<p>Some <span class="sc">html</span> (more precisely hamlet) is written directly inside our handler.
|
|
We should put this part inside another file.
|
|
Create the new file <code>templates/echo.hamlet</code> containing:</p>
|
|
|
|
<div class="codefile"><a href="/Scratch/en/blog/Yesod-tutorial-for-newbies/code/echo.hamlet">➥ echo.hamlet</a></div>
|
|
|
|
<pre><code class="haskell"><h1> #{theText}
|
|
</code></pre>
|
|
|
|
<p>and modify the handler <code>Handler/Echo.hs</code>:</p>
|
|
|
|
<pre><code class="haskell">getEchoR :: Text -> Handler RepHtml
|
|
getEchoR theText = do
|
|
defaultLayout $ do
|
|
$(widgetFile "echo")
|
|
</code></pre>
|
|
|
|
<p>At this point, our web application is structured between different files.
|
|
Handler are grouped, we use <code>Data.Text</code> and our views are in templates.
|
|
It is the time to make a slightly more complex example.</p>
|
|
|
|
<h2 id="mirror">Mirror</h2>
|
|
|
|
<p><img alt="Neo touching a mirror" src="/Scratch/img/blog/Yesod-tutorial-for-newbies/mirror.jpg" class=" left" /></p>
|
|
|
|
<p>Let’s make another minimal application.
|
|
You should see a form containing a text field and a validation button.
|
|
When you enter some text (for example “Jormungad”) and validate,
|
|
the next page present you the content and its reverse appended to it.
|
|
In our example it should return “JormungaddagnumroJ”. </p>
|
|
|
|
<p>First, add a new route:</p>
|
|
|
|
<pre>
|
|
/mirror MirrorR GET POST
|
|
</pre>
|
|
|
|
<p>This time the path <code>/mirror</code> will accept GET and POST requests.
|
|
Add the corresponding new Handler file:</p>
|
|
|
|
<div class="codefile"><a href="/Scratch/en/blog/Yesod-tutorial-for-newbies/code/Mirror.hs">➥ Mirror.hs</a></div>
|
|
|
|
<pre><code class="haskell">module Handler.Mirror where
|
|
|
|
import Import
|
|
import qualified Data.Text as T
|
|
|
|
getMirrorR :: Handler RepHtml
|
|
getMirrorR = do
|
|
defaultLayout $ do
|
|
$(widgetFile "mirror")
|
|
|
|
postMirrorR :: Handler RepHtml
|
|
postMirrorR = do
|
|
postedText <- runInputPost $ ireq textField "content"
|
|
defaultLayout $ do
|
|
$(widgetFile "posted")
|
|
</code></pre>
|
|
|
|
<p>Don’t forget to declare it inside <code>yosog.cabal</code> and <code>Application.hs</code>.</p>
|
|
|
|
<p>We will need to use the <code>reverse</code> function provided by <code>Data.Text</code>
|
|
which explain the additional import.</p>
|
|
|
|
<p>The only new thing here is the line that get the POST parameter named “content”.
|
|
If you want to know more detail about it and form in general you can take
|
|
look at <a href="http://www.yesodweb.com/book/forms">the yesod book</a>.</p>
|
|
|
|
<p>Create the two corresponding templates:</p>
|
|
|
|
<div class="codefile"><a href="/Scratch/en/blog/Yesod-tutorial-for-newbies/code/mirror.hamlet">➥ mirror.hamlet</a></div>
|
|
|
|
<pre><code class="html"><h1> Enter your text
|
|
<form method=post action=@{MirrorR}>
|
|
<input type=text name=content>
|
|
<input type=submit>
|
|
</code></pre>
|
|
|
|
<div class="codefile"><a href="/Scratch/en/blog/Yesod-tutorial-for-newbies/code/posted.hamlet">➥ posted.hamlet</a></div>
|
|
|
|
<pre><code class="html"><h1>You've just posted
|
|
<p>#{postedText}#{T.reverse postedText}
|
|
<hr>
|
|
<p><a href=@{MirrorR}>Get back
|
|
</code></pre>
|
|
|
|
<p>And that is all.
|
|
This time, we won’t need to clean up.
|
|
We may have used another way to generate the form
|
|
but we’ll see this in the next section.</p>
|
|
|
|
<p>Just try it by <a href="http://localhost:3000/mirror">clicking here</a>.</p>
|
|
|
|
<p>Also you can try to enter strange values.
|
|
Like before, your application is quite secure.</p>
|
|
|
|
<h2 id="a-blog">A Blog</h2>
|
|
|
|
<p>We saw how to retrieve <span class="sc">http</span> parameters.
|
|
It is the time to save things into a database.</p>
|
|
|
|
<p>As before add some routes inside <code>config/routes</code>:</p>
|
|
|
|
<pre>
|
|
/blog BlogR GET POST
|
|
/blog/#ArticleId ArticleR GET
|
|
</pre>
|
|
|
|
<p>This example will be very minimal:</p>
|
|
|
|
<ul>
|
|
<li><code>GET</code> on <code>/blog</code> should display the list of articles.</li>
|
|
<li><code>POST</code> on <code>/blog</code> should create a new article</li>
|
|
<li><code>GET</code> on <code>/blog/<article id></code> should display the content of the article.</li>
|
|
</ul>
|
|
|
|
<p>First we declare another model object.
|
|
Append the following content to <code>config/models</code>:</p>
|
|
|
|
<pre>
|
|
Article
|
|
title Text
|
|
content Html
|
|
deriving
|
|
</pre>
|
|
|
|
<p>As <code>Html</code> is not an instance of <code>Read</code>, <code>Show</code> and <code>Eq</code>,
|
|
we had to add the <code>deriving</code> line.
|
|
If you forget it, there will be an error.</p>
|
|
|
|
<p>After the route and the model, we write the handler.
|
|
First, declare a new Handler module.
|
|
Add <code>import Handler.Blog</code> inside <code>Application.hs</code> and add it into <code>yosog.cabal</code>.
|
|
Let’s write the content of <code>Handler/Blog.hs</code>.
|
|
We start by declaring the module and by importing some block necessary to
|
|
handle Html in forms.</p>
|
|
|
|
<pre><code class="haskell">module Handler.Blog
|
|
( getBlogR
|
|
, postBlogR
|
|
, getArticleR
|
|
)
|
|
where
|
|
|
|
import Import
|
|
|
|
-- to use Html into forms
|
|
import Yesod.Form.Nic (YesodNic, nicHtmlField)
|
|
instance YesodNic App
|
|
</code></pre>
|
|
|
|
<p><small>Remark: it is a best practice to add the YesodNic instance inside <code>Foundation.hs</code>.
|
|
I put this definition here to make things easier but you should see a warning about this orphan instance.
|
|
To put the include inside Foundation.hs is left as an exercice to the reader.</small></p>
|
|
|
|
<p><small><em>Hint: Do not forget to put <code>YesodNic</code> and <code>nicHtmlField</code> inside the exported objects of the module.</em>
|
|
</small></p>
|
|
|
|
<pre><code class="haskell">entryForm :: Form Article
|
|
entryForm = renderDivs $ Article
|
|
<$> areq textField "Title" Nothing
|
|
<*> areq nicHtmlField "Content" Nothing
|
|
</code></pre>
|
|
|
|
<p>This function defines a form for adding a new article.
|
|
Don’t pay attention to all the syntax.
|
|
If you are curious you can take a look at Applicative Functor.
|
|
You just have to remember <code>areq</code> is for required form input.
|
|
Its arguments being: <code>areq type label default_value</code>.</p>
|
|
|
|
<pre><code class="haskell">-- The view showing the list of articles
|
|
getBlogR :: Handler RepHtml
|
|
getBlogR = do
|
|
-- Get the list of articles inside the database.
|
|
articles <- runDB $ selectList [] [Desc ArticleTitle]
|
|
-- We'll need the two "objects": articleWidget and enctype
|
|
-- to construct the form (see templates/articles.hamlet).
|
|
(articleWidget, enctype) <- generateFormPost entryForm
|
|
defaultLayout $ do
|
|
$(widgetFile "articles")
|
|
</code></pre>
|
|
|
|
<p>This handler should display a list of articles.
|
|
We get the list from the DB and we construct the form.
|
|
Just take a look at the corresponding template:</p>
|
|
|
|
<div class="codefile"><a href="/Scratch/en/blog/Yesod-tutorial-for-newbies/code/articles.hamlet">➥ articles.hamlet</a></div>
|
|
|
|
<pre><code class="html"><h1> Articles
|
|
$if null articles
|
|
-- Show a standard message if there is no article
|
|
<p> There are no articles in the blog
|
|
$else
|
|
-- Show the list of articles
|
|
<ul>
|
|
$forall Entity articleId article <- articles
|
|
<li>
|
|
<a href=@{ArticleR articleId} > #{articleTitle article}
|
|
<hr>
|
|
<form method=post enctype=#{enctype}>
|
|
^{articleWidget}
|
|
<div>
|
|
<input type=submit value="Post New Article">
|
|
</code></pre>
|
|
|
|
<p>You should remark we added some logic inside the template.
|
|
There is a test and a “loop”.</p>
|
|
|
|
<p>Another very interesting part is the creation of the form.
|
|
The <code>articleWidget</code> was created by yesod.
|
|
We have given him the right parameters
|
|
(input required or optional, labels, default values).
|
|
And now we have a protected form made for us.
|
|
But we have to create the submit button.</p>
|
|
|
|
<p>Get back to <code>Handler/Blog.hs</code>.</p>
|
|
|
|
<pre><code class="haskell">-- we continue Handler/Blog.hs
|
|
postBlogR :: Handler RepHtml
|
|
postBlogR = do
|
|
((res,articleWidget),enctype) <- runFormPost entryForm
|
|
case res of
|
|
FormSuccess article -> do
|
|
articleId <- runDB $ insert article
|
|
setMessage $ toHtml $ (articleTitle article) <> " created"
|
|
redirect $ ArticleR articleId
|
|
_ -> defaultLayout $ do
|
|
setTitle "Please correct your entry form"
|
|
$(widgetFile "articleAddError")
|
|
</code></pre>
|
|
|
|
<p>This function should be used to create a new article.
|
|
We handle the form response.
|
|
If there is an error we display an error page.
|
|
For example if we left some required value blank.
|
|
If things goes right: </p>
|
|
|
|
<ul>
|
|
<li>we add the new article inside the DB (<code>runDB $ insert article</code>)</li>
|
|
<li>we add a message to be displayed (<code>setMessage $ ...</code>)</li>
|
|
<li>we are redirected to the article web page.</li>
|
|
</ul>
|
|
|
|
<p>Here is the content of the error Page:</p>
|
|
|
|
<pre><code class="haskell"><form method=post enctype=#{enctype}>
|
|
^{articleWidget}
|
|
<div>
|
|
<input type=submit value="Post New Article">
|
|
</code></pre>
|
|
|
|
<p>Finally we need to display an article:</p>
|
|
|
|
<pre><code class="haskell">getArticleR :: ArticleId -> Handler RepHtml
|
|
getArticleR articleId = do
|
|
article <- runDB $ get404 articleId
|
|
defaultLayout $ do
|
|
setTitle $ toHtml $ articleTitle article
|
|
$(widgetFile "article")
|
|
</code></pre>
|
|
|
|
<p>The <code>get404</code> function try to do a get on the DB.
|
|
If it fails it return a 404 page.
|
|
The rest should be clear.
|
|
Here is the content of <code>templates/article.hamlet</code>:</p>
|
|
|
|
<div class="codefile"><a href="/Scratch/en/blog/Yesod-tutorial-for-newbies/code/article.hamlet">➥ article.hamlet</a></div>
|
|
|
|
<pre><code class="html"><h1> #{articleTitle article}
|
|
<article> #{articleContent article}
|
|
</code></pre>
|
|
|
|
<p>The blog system is finished.
|
|
Just for fun, you can try to create an article with the following content:</p>
|
|
|
|
<pre><code class="html"><p>A last try to <em>cross script</em>
|
|
and <em>SQL injection</em></p>
|
|
<p>Here is the first try:
|
|
<script>alert("You loose");</script></p>
|
|
<p> And Here is the last </p>
|
|
"); DROP TABLE ARTICLE;;
|
|
</code></pre>
|
|
|
|
<h2 id="conclusion">Conclusion</h2>
|
|
|
|
<p>This is the end of this tutorial.
|
|
I made it very minimal.</p>
|
|
|
|
<p>If you already know Haskell and you want to go further,
|
|
you should take a look at the
|
|
recent <a href="http://yesodweb.com/blog/2012/01/blog-example">i18n blog tutorial</a>.
|
|
It will be obvious I inspired my own tutorial on it.
|
|
You’ll learn in a very straightforward way how easy it is to use authorizations,
|
|
Time and internationalization. </p>
|
|
|
|
<p>If, on the other hand you don’t know Haskell.
|
|
Then you shouldn’t jump directly to web programming.
|
|
Haskell is a very complex and unusual language.
|
|
My advice to go as fast as possible in using Haskell for web programming is:</p>
|
|
|
|
<ol>
|
|
<li>Start by <a href="http://tryhaskell.org">try Haskell in your browser</a></li>
|
|
<li>Then read the excellent <a href="http://learnyouahaskell.com">Learn you a Haskell for Great Good</a></li>
|
|
<li>If you have difficulties in understanding concepts like monads, you should really read <a href="http://homepages.inf.ed.ac.uk/wadler/topics/monads.html">these articles</a>. For me they were enlightening.</li>
|
|
<li>If you feel confident, you should be able to follows the <a href="http://yesodweb.com/book">yesod book</a> and if you find difficult to follows the yesod book, you should read <a href="http://book.realworldhaskell.org">real world Haskell</a> first (it is a must read).</li>
|
|
</ol>
|
|
|
|
<p>Also, note that:</p>
|
|
|
|
<ul>
|
|
<li><a href="http://haskell.org">haskell.org</a> is full of excellent resources.</li>
|
|
<li><a href="http://www.haskell.org/hoogle/">hoogle</a> will be very useful</li>
|
|
<li>Use <a href="http://community.haskell.org/~ndm/hlint/">hlint</a> as soon as possible to get good habits.</li>
|
|
</ul>
|
|
|
|
<p>As you should see, if you don’t already know Haskell,
|
|
the path is long but I guaranty you it will be very rewarding!</p>
|
|
|
|
<p><em>ps:</em> You can download the source of this yesod blog tutorial at
|
|
<a href="http://github.com/yogsototh/yosog">github.com/yogsototh/yosog</a>.</p>
|
|
<hr/><div class="footnotes">
|
|
<ol>
|
|
<li id="fn:benchmarkdigression">
|
|
<p>One can argue these benchmark contains many problems. But the benchmarks are just here to give an order of idea. Mainly Haskell is very fast.<a href="#fnref:benchmarkdigression" rel="reference">↩</a></p>
|
|
</li>
|
|
<li id="fn:speeddigression">
|
|
<p>Generally <em>high level</em> Haskell is slower than C, but <em>low level</em> Haskell is equivalent to C speed. It means that even if you can easily link C code with Haskell, this is not needed to reach the same speed. Furthermore writing a web service in C/C++ seems to be a very bad idea. You can take a look at a <a href="http://news.ycombinator.com/item?id=3449388">discussion on HN about this</a>. <a href="#fnref:speeddigression" rel="reference">↩</a></p>
|
|
</li>
|
|
<li id="fn:nodejstroll">
|
|
<p>If you are curious, you can search about <a href="http://www.unlimitednovelty.com/2011/10/nodejs-has-jumped-shark.html">the Fibonacci node.js troll</a>. Without any tweaking, <a href="http://mathias-biilmann.net/posts/2011/10/is-haskell-the-cure">Haskell handled this problem perfectly</a>. I tested it myself using yesod instead of Snap.<a href="#fnref:nodejstroll" rel="reference">↩</a></p>
|
|
</li>
|
|
<li id="fn:explainviewwidget">
|
|
<p>By view I mean yesod widget’s hamlet, lucius and julius files. <a href="#fnref:explainviewwidget" rel="reference">↩</a></p>
|
|
</li>
|
|
</ol>
|
|
</div>
|
|
|
|
</div>
|
|
|
|
|
|
|
|
<div id="social">
|
|
<div class="left"> <a href="https://twitter.com/share" class="twitter-share-button" data-via="yogsototh">Tweet</a>
|
|
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
|
|
</div>
|
|
<div class="left"> <div class="g-plusone" data-size="medium" data-annotation="inline" data-width="106"></div>
|
|
<script type="text/javascript">
|
|
(function() {
|
|
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
|
|
po.src = 'https://apis.google.com/js/plusone.js';
|
|
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
|
|
})();
|
|
</script>
|
|
</div>
|
|
<div class="flush"></div>
|
|
</div>
|
|
<div id="choixrss">
|
|
<a id="rss" href="http://feeds.feedburner.com/yannespositocomen">
|
|
Subscribe
|
|
</a>
|
|
</div>
|
|
<script type="text/javascript">
|
|
$(document).ready(function(){
|
|
$('#comment').hide();
|
|
$('#clickcomment').click(showComments);
|
|
});
|
|
function showComments() {
|
|
$('#comment').show();
|
|
$('#clickcomment').fadeOut();
|
|
}
|
|
document.write('<div id="clickcomment">Comments & Share</div>');
|
|
</script>
|
|
<div class="flush"></div>
|
|
|
|
<div class="corps" id="comment">
|
|
<h2 class="first">comments</h2>
|
|
<noscript>
|
|
You must enable javascript to comment.
|
|
</noscript>
|
|
|
|
<script type="text/javascript">
|
|
var idcomments_acct = 'a307f0044511ff1b5cfca573fc0a52e7';
|
|
var idcomments_post_id = '/Scratch/en/blog/Yesod-tutorial-for-newbies/';
|
|
var idcomments_post_url = 'http://yannesposito.com/Scratch/en/blog/Yesod-tutorial-for-newbies/';
|
|
</script>
|
|
<span id="IDCommentsPostTitle" style="display:none"></span>
|
|
<script type='text/javascript' src='/Scratch/js/genericCommentWrapperV2.js'></script>
|
|
|
|
</div>
|
|
|
|
<div id="entete" class="corps_spaced">
|
|
<div id="liens">
|
|
<ul><li><a href="/Scratch/en/">Home</a></li>
|
|
<li><a href="/Scratch/en/blog/">Blog</a></li>
|
|
<li><a href="/Scratch/en/softwares/">Softwares</a></li>
|
|
<li><a href="/Scratch/en/about/">About</a></li></ul>
|
|
</div>
|
|
<div class="flush"></div>
|
|
<hr/>
|
|
<div id="next_before_articles">
|
|
<div id="previous_articles">
|
|
previous entries
|
|
|
|
<div class="previous_article">
|
|
<a href="/Scratch/en/blog/SVG-and-m4-fractals/"><span class="nicer">«</span> Increase the power of deficient languages.</a>
|
|
</div>
|
|
|
|
|
|
<div class="previous_article">
|
|
<a href="/Scratch/en/blog/Yesod-excellent-ideas/"><span class="nicer">«</span> Yesod excellent ideas</a>
|
|
</div>
|
|
|
|
|
|
<div class="previous_article">
|
|
<a href="/Scratch/en/blog/Higher-order-function-in-zsh/"><span class="nicer">«</span> Higher order function in zsh</a>
|
|
</div>
|
|
|
|
|
|
</div>
|
|
<div id="next_articles">
|
|
next entries
|
|
|
|
<div class="next_article">
|
|
<a href="/Scratch/en/blog/Typography-and-the-Web/">Typography and the Web <span class="nicer">»</span></a>
|
|
</div>
|
|
|
|
|
|
<div class="next_article">
|
|
<a href="/Scratch/en/blog/Haskell-the-Hard-Way/">Learn Haskell Fast and Hard <span class="nicer">»</span></a>
|
|
</div>
|
|
|
|
|
|
|
|
</div>
|
|
<div class="flush"></div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="bottom">
|
|
<div>
|
|
<a href="https://twitter.com/yogsototh">Follow @yogsototh</a>
|
|
</div>
|
|
<div>
|
|
<a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/">Copyright ©, Yann Esposito</a>
|
|
</div>
|
|
<div id="lastmod">
|
|
Created: 01/15/2012
|
|
Modified: 05/02/2012
|
|
</div>
|
|
<div>
|
|
Entirely done with
|
|
<a href="http://www.vim.org">Vim</a>
|
|
and
|
|
<a href="http://nanoc.stoneship.org">nanoc</a>
|
|
</div>
|
|
</div>
|
|
<div class="clear"></div>
|
|
</div>
|
|
</body>
|
|
</html> |