Yesod (web framework)
Yesod is a free and open-source web framework based on Haskell for productive development of type-safe, REST model based, high performance web applications, developed by Michael Snoyman et al.
Yesod is based on templates, to generate instances for listed entities, and dynamic content process functions, through Template Haskell constructs to host eDSL content templates called QuasiQuotes, where the content is translated into code expressions by metaprogramming instructions.
There are also web-like language snippet templates that admit code expression interpolations, making them fully type-checked at compile-time.
Yesod divides its functionality in separate libraries, so you may choose your functionality library of your choice.
MVC architecture
Controller
Server interface
Yesod uses a Web application interface API, abbreviated WAI, to isolate servlets, aka web apps., from servers, with handlers for the server protocols CGI, FastCGI, SCGI, Warp, Launch,The ''foundation'' type
See ref. Yesod requires a data type that instantiates the controller classes. This is called the foundation type. In the example below, it is named "MyApp".The REST model identifies a web resource with a web path. Here REST resources are given names with an R suffix and are listed in a parseRoutes site map description template. From this list, route names and dispatch handler names are derived.
Yesod makes use of Template Haskell metaprogramming to generate code from templates at compile time, assuring that the names in the templates match and everything typechecks.
By inserting a mkYesod call, this will call Template Haskell primitives to generate the code corresponding to the route type members, and the instances of the dispatch controller classes as to dispatch GET calls to route HomeR to a routine named composing them both as "getHomeR", expecting an existing handler that matches the name.
Hello World
"Hello world" example based on a CGI server interface :import "wai" Network.Wai
import "wai-extra" Network.Wai.Handler.CGI -- interchangeable WAI handler
import "yesod" Yesod
import "yesod-core" Yesod.Handler
import "text" Data.Text
import "shakespeare" Text.Cassius
-- the Foundation type
data MyApp = MyApp
-- sitemap template, listing path, resource name and methods accepted
-- `mkYesod` takes the foundation type name as param. for name composition of dispatch functions
mkYesod "MyApp" → CssUrl url
myStyle paramStyle =
→ colorBlack
_ → Color 0 0 255
-- indentation structured HTML template
myHtml :: → HtmlUrl url
myHtml params =
Hello World! There are Nothing to list
$if null params
$else
$forall param <- params
getHomeR :: Handler RepHtml
getHomeR = do
req <- getRequest
let params = reqGetParams req
paramStyle <- lookupGetParams "style"
defaultLayout $ do
-- adding widgets to the Widget monad
setTitle "Yesod example"
toWidgetHead $ myStyle paramStyle
toWidgetBody $ myHtml params
-- there are run function variants for different WAI handlers
main = toWaiApp MyApp >>= run
- cgi test
export REQUEST_METHOD=GET
export PATH_INFO=/
export QUERY_STRING='p1=abc;p2=def;style=high-contrast'
./wai-cgi-hello
Resources, routes and REpresentational State Transfer model of access to [web documents">HTTP method handlers
See ref.Yesod follows the REpresentational State Transfer model of access to [web documents, identifying docs. and directories as resources with a Route constructor, named with an uppercase R suffix.
;The routes table: The parseRoutes template should list the resources specifying route pieces, resource name and dispatch methods to be accepted.
URL segment capture as parameter is possible specifying a '#' prefix for single segment capture or '*' for multisegment capture, followed by the parameter type.
-- given a MyApp foundation type
mkYesod "MyApp"
- Applying the previous template generates the following route constructors:
data Route MyApp =
HomeR -- referenced in templates as: @
| BlogR -- in templates: @
| ArticleR ArticleId -- in templates: @
| BranchR Texts -- in templates: @
- For every supported HTTP method a handler function must be created to match the dispatch names generated by mkYesod from the parseRoutes template, by prefixing the method name to the resource, as described :
-- for "/ HomeR" -- no http methods stated ⇒ only one handler with prefix handler''
handlerHomeR :: HasReps t ⇒ Handler t
-- for "/blog BlogR GET POST"
getBlogR :: HasReps t ⇒ Handler t
postBlogR :: HasReps t ⇒ Handler t
-- for "/article/#ArticleId ArticleR GET PUT"
getArticleR :: HasReps t ⇒ ArticleId → Handler t
putArticleR :: HasReps t ⇒ ArticleId → Handler t
Request data, Parameters, Cookies, Languages and other Header info
See ref.Authentication and authorization
See ref. Authentication plugins: OpenId, BrowserId, Email, GoogleEmail, HashDB, RpxNow.Sessions
See ref. Session back-ends: ClientSession, ServerSessionSession messages
A success, failure or indicative message can be stored in the Session and will be shown, if it exists, by the default_layout routine through thedefault_layout.hamlet
template, being cleared on consultation.Subsites
Common URL prefix subsites for workflows, file serving or site partitioning. See ref.Built-in subsites: Static, Auth
Form processing and layout generation
See ref.The Form type here is an object that is used in the controller to parse and process the form fields user input and produce a pair were the widget holds the layout of the next rendering of the form with error messages and marks. It can also be used to generate a new form with blanks or default values.
The form type takes the shape of a function of an html snippet to be embedded in the view, that will hold security purpose hidden fields.
A form object is generated from an Applicative/Monadic composition of fields for a combined/sequential parsing of field inputs.
There are three types of forms:
- Applicative,
- Monadic, both in the Yesod.Form.Functions module,
- Input in the Yesod.Form.Input module.
followed by
, have a fieldParse component and a fieldView one. - the function runForm runs the field parsers against the form field inputs and generates a pair from the views offering a new form widget with the received form field values as defaults. The function suffix is the http method used in the form submission.
- while generateForm ignores inputs from the client and generates a blank or defaults form widget.
The magic is in the FormResult data type Applicative instance, where collects the error messages for the case of
FormFailure
result valuesMonadic forms permit free form layout and better treatment of hiddenField members.
A sample of an Applicative form:
-- a record for our form fields
data Person = Person
-- the Form type has an extra parameter for an html snippet to be embedded, containing a CSRF token hidden field for security
type Form sub master x = Html → MForm sub master
personForm :: MyFoundationType → → Maybe Person → Form sub master Person
personForm master languages mbPersonDefaults = renderTable $
Person <$> areq textField fldSettingsName mbNameDefault
<*> areq customPersonAgeField fldSettingsAge mbAgeDefault
<*> aopt textareaField fldSettingsLikings mbLikingsDefault
where
mbNameDefault = fmap personName mbPersonDefaults
mbAgeDefault = fmap personAge mbPersonDefaults
mbLikingsDefault = fmap personLikings mbPersonDefaults
-- "fieldSettingsLabel" returns an initial fieldSettings record
-- recently the "FieldSettings" record can be defined from a String label since it implements IsString
fldSettingsName =
fldSettingsAge = fieldSettingsLabel MsgAge
fldSettingsLikings =
customPersonAgeField = check validateAge intField
validateAge y
| y < 18 = Left $ renderMessage master languages MsgUnderAge
| otherwise = Right y
View
The types shown correspond to an older version, but the philosophy remains.The Handler monad returns content in one or more of several formats as components of types that implement the HasReps class. Json examples:
The HasReps default implementation of chooseRep chooses the document representation to be returned according to the preferred content-type list of the client accept header.
- Widgets are HTML DOM code snippets made by specific commands or from templates of structure / behaviour / style, whose types instantiate the classes ToWidget, ToWidgetHead or ToWidgetBody.
Indentation based templates for tree structured markup
- the hamlet quasiquoter specified in the T.H. Oxford brackets syntax
introduces an indentation based structured html template..
Automatic closing tags are generated only for the tag at line start position.
- the whamlet quasiquoter returns a Widget expression..
toWidget
$doctype 5
^
_
$if null articles
$else
$forall art <- articles
Template interpolation - ''Shakespearean templates''
See ref.These are content view templates that follow a common substitution pattern of code expressions within curly brackets with different character prefix to refer to
; template expressions with
^
: refers to other templates of the same type, with given parameters as ^
,; route expressions with
@
: safe urls as @
,; message expressions with
_
: [i18n message rendering as _
; other Haskell expressions with
#
: haskell expression rendering as #
which type must be convertible- * in case of hamlet html templates, the expression type must be an instance of Text.Blaze.ToMarkup
- * in case of css templates, the expression type must be an instance of Text.Cassius.ToCss
- * in case of JavaScript templates, the expression type must be an instance of Text.Julius.ToJavascript
- * in case of i18n message definitions with parameter interpolations, the expression type must be an instance of Text.Shakespeare.I18N.ToMessage
- * in case of text/plain templates, the expression type must be an instance of Text.Shakespeare.Text.ToText
; External file templates:
- at compile time: Template content can be loaded from external files using compile time splice calls as $.
- at run time: There is a reload mode for reparsing external template files at every service call, except for HTML hamlet templates: See doc.
Other templates
;for CSS:
- the cassius quasiquoter: introduces a css template with indentation based structuring.
- the lucius quasiquoter: introduces a css template with standard syntax plus shakespeare-template style substitutions.
; text/plain templates: for e-mail or text/plain http content type.
- templates: lt: lazy text, st: strict text
- templates for text with a left margin delimiter '|': lbt, sbt
Localizable messages
Yesod app messages are localizable. They should be held within the messages folder, in files named based on ISO, as <iso-language>.msg
Message entries follow the EBNF pattern:
-- EBNF: identifier,, ":", text with interpolations
ArticleUnexistent param@Int64 : unexistent article #
- message constructors are formed prepending "Msg" to the message label identifier.
- the message datatype is formed appending "Message" to the foundation type name.
-- in code
myMsg :: MyAppMessage -- datatype appending "Message" to the foundation type
myMsg = MsgArticleUnexistent myArticleId -- constructor prepending "Msg" to the msg. label
-- in widget templates
_
Actual i18n support is missing from the stack app template. You have to add the
mkMessage "MyApp" messagesFolder isoLangDefault
to the "Foundation.hs" file to get the messages instantiated.Navigation Breadcrumbs
- Navigation Breadcrumbs. You have to provide a YesodBreadcrumbs instance for the site where the generator function breadcrumb should return for each route a title and parent one. Then, the query function breadcrumbs will return the present route title and the ancestors' pairs.
Search engine XML Sitemap
- Search engines XML Sitemaps, where sitemap returns an XML Sitemap as http response, with the routes we want the search engines to crawl, and attributes to instruct the crawler, from a provided list of SitemapUrl records.
Web feed views
- Web feed views. You have handlers that return RepRss, RepAtom, or dual RepAtomRss content from a given Feed structure.
Model
Using in-memory mutable data (in the foundation datatype)
E.g. a visitor count. See ref.The Database layer
- persistent is the name of the database access layer with templates for generating types for entities and keys as well as schema initialization.
The Database layout is described in a template listing the entities, fields and constraints.
- For every entity listed, an integer key column "id" is generated with autoincrement and primary index attributes, with a type alias appending Id to the entity name
- For every entity listed, a record type named as the entity is generated were record fields names are composed prefixing the entity name to the field name like "personName". An EntityField type "PersonName" is also generated for foreign key referencing from other entities.
- There is an automatic database schema migration mechanism for DB schema updates, which, to succeed, requires, when adding columns to existent tables, to specify 'Default-column-value constraints with sql level notation.
- "At most one" cardinality has a special mechanism around the type Checkmark.
- Weak entities have no special support for cascade delete triggers, but there are functions to deleteCascade manually in the Database.Persist.Class module.
share
User -- table name and entity record type
-- implicit autoincrement column "id" as primary key, typed UserId
ident Text -- refers to db. table column "ident";
-- generates a record field prefixing the table name as "userIdent"
password Text Maybe -- Maybe indicates Nullable field
UniqueUser ident -- unique constraint with space sep. field sequence
Email -- table name and entity record type
-- implicit autoincrement column "id" as primary key, typed EmailId
email Text
user UserId -- foreign key by specifying other tables EntityField types
verkey Text Maybe
newlyAddedColumn Text "default='sometext'::character varying" -- sql level Default constraint
UniqueEmail email -- unique constraint
- Esqueleto: is a haskell combinators layer to generate correct relational queries to
- email-validate: Validating an email address.
- mime-mail: Compose and send MIME email messages.
Facebook
- Useful glue functions between the fb library and Yesod.
Development cycle
Stack based app. template names are prefixed by yesod as "yesod-"
- Since HaskellStack uses the stackage repo [by default, extra packages from the hackage repo should be referred in the "stack.yaml" extra-deps section.
- You may customize packages to a local subfolder. They must be referred in the "stack.yaml" packages section.
The "Yesod helper" tool
- The yesod helper tool
- *
yesod devel
run from the project site, recompiles and restarts the project at every file tree modification. - *
yesod add-handler
adds a new handler and module to the project, adding an import clause for the handler in the "Application" module.Deploying with Keter: A web app server monitor and reverse proxy server
Keter is a process as a service that handles deployment and restart of Yesod web app servers, and, per web app, database creation for PostgreSQL.
The console command
yesod keter
packs the web app. as a keter bundle for uploading to a keter folder named "incoming".Keter monitors the "incoming" folder and unpacks the app. to a temporary one, then assigns the web app a port to listen to, and starts it.
Initially it worked with Nginx as reverse proxy, adding virtual server entries to its configuration and making Nginx reload it, but now Keter itself provides its own reverse proxy functionality, removing Nginx dependency and acting as the main web server.
Old documentation.
Integration with [JavaScript] generated from functional languages
See ref.Blog tutorials
- ,
-
Comparisons
-
Other languages
- Univ. of Cadiz
At GNU/Linux distributions