Haskell+Yesod入门教程

Quick Start

Haskell是一个比较偏的语言,但是对于理解函数式编程很有帮助,在日后使用其他函数式语言会有所帮助,比如说sacla语言。下面做一个Yesod Framework的教程。

Yesod是y一个Haskell的Web框架。

运行环境

基于haskell进行构建。

  1. Follow the haskell-lang get started guide to get the Stack build tool.

    On POSIX systems, this is usually

    1
    curl -sSL https://get.haskellstack.org/ | sh
  2. Create a new scaffolded site:

    1
    stack new my-project yesod-sqlite && cd my-project

    NOTE: Use stack templates to see other available Yesod scaffoldings.

  1. Install the yesod command line tool:

    1
    stack install yesod-bin --install-ghc
  2. Build libraries:

    1
    stack build
  3. Launch devel server:

    1
    stack exec -- yesod devel
  4. View your Yesod site at http://localhost:3000/

  5. Add Handler

    1
    stack exec -- yesod add-handler

Hello World

这里我们编写一个Hello World的实例介绍

  1. 在templeates目录下创建一个文件hello.hamlet。

这是一个页面文件,相当于动态web语言中的页面,需要注意的是,在这里不需要写结尾标签。(搞不懂这个设计有啥好处)

1
2
3
4
<div .ui.container>
<h1>Hello

<a href='#'>Go to World
  1. 修改路由文件config/routes

<请求路径> <控制层> <请求类型>

1
/hello HelloR GET
  1. 编写控制层src/Handler/Hello.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
module Handler.Hello where

import Import

getHelloR :: Handler Html
getHelloR = do
(_, user) <- requireAuthPair
defaultLayout $ do
setTitle . toHtml $ userIdent user <> "'s User page"
$(widgetFile "hello")

访问测试

1
stack exec -- yesod devel

打开浏览器:http://localhost:3000/hello

其他

More info: 官网

Fiveplus wechat
扫一扫上方二维码,关注微信公众号:阿五编程
如果这篇文章对你有所帮助,请点击下方的打赏按钮。