fbpx
Wikipedia

Yesod (web framework)

This article is about the Haskell web framework. For the kabbalistic concept, see Yesod.
This article has multiple issues. Please help improve it or discuss these issues on the talk page. ()
This article is written like a manual or guidebook. Please help rewrite this article from a descriptive, neutral point of view, and remove advice or instruction.(September 2018) ()
This article relies too much on references to primary sources. Please improve this by adding secondary or tertiary sources.(September 2018) ()
This article contains instructions, advice, or how-to content. The purpose of Wikipedia is to present facts, not to train. Please help improve this article either by rewriting the how-to content or by moving it to Wikiversity, Wikibooks or Wikivoyage.(September 2018)
()

Yesod (IPA: ; Hebrew:יְסוֺד‎, "Foundation") is a free and open-source web framework based on Haskell for productive development of type-safe, REST model based (where URLs identify resources, and HTTP methods identify transitions), 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 {database, html rendering, forms, etc.} functionality library of your choice.

Contents

See also: MVC

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 (open as local URL to the default browser, closing the server when the window is closed),

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 (like "HomeR") 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 (e.g. web resource names and handler names).

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 (The actual handler types have changed, but the philosophy remains):

Resources, routes and 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 (for example, HomeR).

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.

  • Applying the previous template generates the following route constructors:
  • 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 (or the prefix "handler" if no method stated) to the resource, as described (actual versions handler types have changed, but the philosophy remains):

Request data, Parameters, Cookies, Languages and other Header info

See ref.

Authentication and authorization

See ref. Authentication plugins: OpenId, BrowserId, Email, GoogleEmail, HashDB, RpxNow.

There is an important setting for automatic redirection after authentication.

Sessions

See ref. Session back-ends: ClientSession (it stores the session in a cookie), ServerSession (it stores most of the session data at the server)

>> To avoid undue bandwidth overhead, production sites can serve their static content from a separate domain name to avoid the overhead of transmitting the session cookie for each request
Session messages

A success, failure or indicative message can be stored (setMessage) in the Session and will be shown, if it exists, by the default_layout routine through the default_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 (FormResult, Widget) 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 (with tabular layout),
  • Monadic (with free layout style), both in the Yesod.Form.Functions module,
  • Input (for parsing only, no view generated) in the Yesod.Form.Input module.

The field generators, whose names are composed by the form type initial (a|m|i) followed by (req|opt){- required or optional -}, have a fieldParse component and a fieldView one.

  • the function runForm{Post|Get} runs the field parsers against the form field inputs and generates a (FormResult, Widget) 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{Post|Get} ignores inputs from the client and generates a blank or defaults form widget.

The actual function parameters and types have changed through Yesod versions. Check the Yesod book and libraries signatures.

The magic is in the FormResult data type Applicative instance, where (<*>) collects the error messages for the case of FormFailure [textErrMsg] result values

Monadic forms permit free form layout and better treatment of hiddenField members.

A sample of an Applicative form:

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 {RepHtml, RepJson, RepXml, RepPlain, the dual RepHtmlJson, a pair or list of pairs [(ContentType, Content)], ..}. 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 (e.g. setTitle) or from templates of structure (html) / behaviour (JavaScript) / style (css), whose types instantiate the classes ToWidget, ToWidgetHead or ToWidgetBody.

A Widget monad, based on a Writer one and argument to defaultLayout, facilitate to piece the widgets together.

Indentation based templates for tree structured markup

  • the hamlet quasiquoter (a parser to compile-time Template Haskell code) specified in the T.H. Oxford brackets syntax [qq| ... |] introduces an indentation based structured html template. (See doc.).

'$' prefixes lines of logic statements.

Automatic closing tags are generated only for the tag at line start position.

  • the whamlet quasiquoter returns a Widget expression. (saves to Widget before [hamlet|..|]).
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 ^{template params},
route expressions with @{...}
safe (typed) urls as @{HomeR},
message expressions with _{...}
i18n message rendering as _{MsgMessageLabel params}
other Haskell expressions with #{...}
haskell expression rendering as #{haskell_expression} 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 (in "<isoLanguage>.msg" files) with parameter interpolations, the expression type must be an instance of Text.Shakespeare.I18N.ToMessage
  • in case of text/plain templates (for use in emails), the expression type must be an instance of Text.Shakespeare.Text.ToText

Using non-English text in expressions requires use of the Unicode-aware type Text, since GHC's show for the type String renders non-ASCII characters as escaped numerical codes.

External file templates
  • at compile time: Template content can be loaded from external files using compile time splice calls as $(expr).
  • 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 JavaScript, CoffeeScript, Roy
the julius quasiquoter: introduces a JavaScript template. JavaScript variants CoffeeScript and Roy-language have also specific quasiquoters.
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.
TypeScript and JSX templates
the tsc and tscJSX quasiquoters. Only on UNIX derivatives (no Windows by now).
text/plain templates
for e-mail or text/plain http content type.
  1. templates: lt: lazy text, st: strict text
  2. templates for text with a left margin delimiter '|': lbt (lazy), sbt (strict)

Localizable messages

See ref.

Yesod app messages are localizable (i18n). They should be held within the messages folder, in files named based on ISO, as <iso-language>.msg

Message entries follow the EBNF pattern:

  • message constructors are formed prepending "Msg" to the message label identifier.
  • the message datatype is formed appending "Message" to the foundation type name.

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' (route, title) 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 (RSS / Atom). You have handlers that return RepRss, RepAtom, or dual RepAtomRss content (to be selected on accept headers' preferred content-type list) 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.

There is first class support for PostgreSQL, SQLite, MongoDB, CouchDB and MySQL, with experimental support for Redis.

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 (childs in life constrained owner-child relationships) have no special support for cascade delete triggers, but there are functions to deleteCascade manually in the Database.Persist.Class module.
automatic table creation, schema update and table migration
Modifications of the entities template produces an schema update with automatic table creation, and migration for the DBMS's that support "ALTER TABLE" SQL commands in a migrateAll procedure, generated from the template content. See "Migrations" in ref. to look for migration aware DBMS.
  • Esqueleto: is a haskell combinators layer to generate correct relational queries to persistent.

Example for persistent rawSQL and Esqueleto queries.

E-mail

The following packages are part of the yesod-platform:

  • email-validate: Validating an email address.
  • mime-mail: Compose and send MIME email messages.

Facebook

  • Useful glue functions between the fb library and Yesod.

New Yesod apps are generated from the HaskellStack tool templates, replacing previous command "yesod init"

Stack based app. template names are prefixed by yesod as "yesod-{minimal | postgres | sqlite | mysql | mongo | ...}"

  • 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

See refs.

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 (keter version 0.1*), 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 (Nginx based).

See ref.

  1. "yesodweb / yesod". github.com. Retrieved13 June 2020.
  2. "HaskellWiki - QuasiQuotation". Haskell.org. 2012-05-26. Retrieved2012-10-23.
  3. "Univ. of Kent - Comparing Dynamic and Static Language Approaches to Web Frameworks - Yesod vs Ruby on Rails"(PDF). Retrieved2012-10-23.
  4. "The wai package". Hackage.haskell.org. Retrieved2012-10-23.
  5. "The wai-extra package with CGI WAI handler". Hackage.haskell.org. Retrieved2012-10-23.
  6. "The wai-handler-fastcgi package". Hackage.haskell.org. Retrieved2012-10-23.
  7. "The wai-handler-scgi package". Hackage.haskell.org. Retrieved2012-10-23.
  8. "The warp package". Hackage.haskell.org. Retrieved2012-10-23.
  9. "The wai-handler-launch package". Hackage.haskell.org. Retrieved2012-10-23.
  10. "book - Basics". Yesodweb.com. Retrieved2012-10-23.
  11. The mkYesod code
  12. "book - Routing and Handlers". Yesodweb.com. Retrieved2012-10-23.
  13. "Playing with Routes and Links". FPComplete.com. 2012-10-17. Retrieved2012-10-28.
  14. "book - Authentication and Authorization". Yesodweb.com. Retrieved2012-10-23.
  15. "The yesod-auth package". Hackage.haskell.org. Retrieved2012-10-26.
  16. "book - Sessions - See section "Ultimate Destination"". Yesodweb.com. Retrieved2012-11-17.
  17. "Sessions". Yesodweb.com. Retrieved2012-10-23.
  18. "Web.ClientSession". Hackage.haskell.org. Retrieved2012-10-25.
  19. "ServerSession: secure modular server-side sessions". Hackage.haskell.org. Retrieved2018-10-29.
  20. "Web.ServerSession.Frontend.Yesod". Hackage.haskell.org. Retrieved2018-10-29.
  21. "Session Messages". Yesodweb.com. Retrieved2018-10-23.
  22. "Creating a Subsite". Yesodweb.com. Retrieved2012-10-25.
  23. "Yesod and subsites: a no-brainer". Monoid.se. 2012-08-22. Retrieved2012-10-28.[]
  24. "The Magic of Yesod, part 2 - See section "Static Subsite"". Yesodweb.com. 2010-12-25. Retrieved2012-10-25.
  25. "The package yesod-static - Static Subsite". Hackage.haskell.org. Retrieved2012-10-25.
  26. "The package yesod-auth - Auth Subsite". Hackage.haskell.org. Retrieved2012-10-25.
  27. "book - Forms". Yesodweb.com. Retrieved2012-10-23.
  28. "Yesod.Form.Fields". Hackage.haskell.org. Retrieved2012-10-23.
  29. "Yesod.Form.Functions runFormPost". Hackage.haskell.org. Retrieved2012-10-25.
  30. "Yesod.Form.Types". Hackage.haskell.org. Retrieved2012-10-23.
  31. "HaskellWiki - Applicative functor". haskell.org. Retrieved2012-10-24.
  32. "The class HasReps". Hackage.haskell.org. Retrieved2012-10-23.
  33. "RESTful Content". Yesodweb.com. Retrieved2012-10-23.
  34. "The class ToContent". Hackage.haskell.org. Retrieved2012-10-23.
  35. "More Client Side Yesod: todo sample". Yesodweb.com. 2012-04-23. Retrieved2012-10-23.
  36. "JSON Web Service". Yesodweb.com. Retrieved2012-10-23.
  37. "The yesod-json package". Hackage.haskell.org. Retrieved2012-10-23.
  38. "book - Widgets". Yesodweb.com. Retrieved2012-10-23.
  39. "The widget monad". Hackage.haskell.org. Retrieved2012-10-23.
  40. "The Writer monad". Haskell.org. Retrieved2012-10-23.
  41. "Template Haskell Quasi-quotation". Haskell.org. Retrieved2012-11-02.
  42. "book - Shakesperean templates". Yesodweb.com. Retrieved2012-10-23.
  43. "The hamlet template module". Hackage.haskell.org. Retrieved2012-10-23.
  44. "Class Text.Blaze.ToMarkup". Hackage.haskell.org. Retrieved2012-10-23.
  45. "Class Text.Cassius.ToCss". Hackage.haskell.org. Retrieved2012-10-23.
  46. "Class Text.Julius.ToJavascript". Hackage.haskell.org. Retrieved2012-10-23.
  47. "Class Text.Shakespeare.I18N.ToMessage". Hackage.haskell.org. Retrieved2012-10-24.
  48. "Class Text.Shakespeare.Text.ToText". Hackage.haskell.org. Retrieved2012-10-24.
  49. "Template Haskell". haskell.org. Retrieved2012-11-03.
  50. "book - Shakesperean templates # Calling shakespeare". Yesodweb.com. Retrieved2012-10-23.
  51. "The Julius template module". Hackage.haskell.org. Retrieved2012-10-23.
  52. "Roy language". Roy.brianmckenna.org. Retrieved2012-10-23.
  53. "The Cassius template module". Hackage.haskell.org. Retrieved2012-10-23.
  54. "The Lucius template module". Hackage.haskell.org. Retrieved2012-10-23.
  55. "The Typescript template module". Hackage.haskell.org. Retrieved2018-10-10.
  56. "Shakespeare plain text templates module". Hackage.haskell.org. Retrieved2012-10-24.
  57. "book - Internationalization". Yesodweb.com. Retrieved2012-10-23.
  58. mkMessage
  59. "The YesodBreadcrumbs class". Hackage.haskell.org. Retrieved2012-11-05.
  60. "The yesod-sitemap package". Hackage.haskell.org. Retrieved2012-10-26.
  61. "The yesod-newsfeed package for RSS / Atom views". Hackage.haskell.org. Retrieved2012-10-26.
  62. "Book - Initializing data in the foundation datatype". Yesodweb.com. Retrieved2014-05-26.
  63. "book - Persistent". Yesodweb.com. Retrieved2012-10-23.
  64. "Yesod-persistent package". Hackage.haskell.org. Retrieved2012-10-23.
  65. "Yesod-persistent docs". github.com. Retrieved2018-10-16.
  66. "Yesod-persistent entity syntax". github.com. Retrieved2018-10-16.
  67. "Redundant migrations for fields' default values". GitHub.com. Retrieved2012-12-04.
  68. ""At most one" cardinality enforcement in persistent with type Checkmark". Hackage.haskell.org. Retrieved2018-10-16.
  69. "How can I create a foreign key constraint using Yesod/Persistent?". stackoverflow.com. Retrieved2018-10-16.
  70. "esqueleto package". Hackage.haskell.org. Retrieved2012-10-23.
  71. "Query example at". Stackoverflow.com. 2012-09-19. Retrieved2012-10-23.
  72. "The yesod package". Hackage.haskell.org. Retrieved2019-06-26.
  73. "The email-validate package". Hackage.haskell.org. Retrieved2012-10-26.
  74. "The mime-mail package". Hackage.haskell.org. Retrieved2012-10-26.
  75. "The yesod-fb package". Hackage.haskell.org. Retrieved2012-10-26.
  76. Haskell Stack - How to install
  77. The yesod-bin pkg with the helper tool (with instructions for use with the stack tool)
  78. "book - Deploying your Webapp". Yesodweb.com. Retrieved2012-10-23.
  79. Readme.Md. "Yesod keter readme". GitHub. Retrieved2012-10-23.
  80. "The keter package". Hackage.haskell.org. Retrieved2012-10-23.
  81. "Keter updates". Yesodweb.com. 2012-10-25. Retrieved2012-10-25.
  82. "Keter: Web App Deployment". Yesodweb.com. 2012-05-11. Retrieved2012-10-23.
  83. "Keter: It's Alive!". Yesodweb.com. 2012-05-17. Retrieved2012-10-23.
  84. "Javascript Options". github.com. Retrieved2014-03-12.
  85. "Yesod, AngularJS and Fay". yesodweb.com. 2012-10-30. Retrieved2014-03-12.
  86. "HaskellWiki - The JavaScript Problem". haskell.org. Retrieved2014-04-12.

Blog tutorials

Comparisons

Other languages

At Linux distributions

Yesod (web framework)
Yesod web framework Language Watch Edit This article is about the Haskell web framework For the kabbalistic concept see Yesod This article has multiple issues Please help improve it or discuss these issues on the talk page Learn how and when to remove these template messages This article is written like a manual or guidebook Please help rewrite this article from a descriptive neutral point of view and remove advice or instruction September 2018 Learn how and when to remove this template message This article relies too much on references to primary sources Please improve this by adding secondary or tertiary sources September 2018 Learn how and when to remove this template message This article contains instructions advice or how to content The purpose of Wikipedia is to present facts not to train Please help improve this article either by rewriting the how to content or by moving it to Wikiversity Wikibooks or Wikivoyage September 2018 Learn how and when to remove this template message Yesod IPA je sod Hebrew י סו ד Foundation is a free and open source web framework based on Haskell for productive development of type safe REST model based where URLs identify resources and HTTP methods identify transitions high performance web applications developed by Michael Snoyman et al YesodOriginal author s Michael SnoymanDeveloper s Michael Snoyman et al Initial release2010Stable release1 6 18 1 2020 05 31 Repositorygithub wbr com wbr yesodweb wbr yesodWritten inHaskellOperating systemCross platformAvailable inHaskellTypeWeb frameworkLicenseMIT LicenseWebsitewww wbr yesodweb wbr com 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 2 There are also web like language snippet templates that admit code expression interpolations making them fully type checked at compile time 3 Yesod divides its functionality in separate libraries so you may choose your database html rendering forms etc functionality library of your choice Contents 1 MVC architecture 1 1 Controller 1 1 1 Server interface 1 1 2 The foundation type 1 1 3 Hello World 1 1 4 Resources routes and HTTP method handlers 1 1 5 Request data Parameters Cookies Languages and other Header info 1 1 6 Authentication and authorization 1 1 7 Sessions 1 1 7 1 Session messages 1 1 8 Subsites 1 1 9 Form processing and layout generation 1 2 View 1 2 1 Indentation based templates for tree structured markup 1 2 1 1 Template interpolation Shakespearean templates 1 2 1 2 Other templates 1 2 2 Localizable messages 1 2 3 Navigation Breadcrumbs 1 2 4 Search engine XML Sitemap 1 2 5 Web feed views 1 3 Model 1 3 1 Using in memory mutable data in the foundation datatype 1 3 2 The Database layer 1 4 E mail 1 5 Facebook 2 Development cycle 2 1 The Yesod helper tool 2 2 Deploying with Keter A web app server monitor and reverse proxy server 3 Integration with JavaScript generated from functional languages 4 See also 5 References 6 External links 6 1 Blog tutorials 6 2 Comparisons 6 3 Other languages 6 4 At Linux distributionsMVC architecture EditSee also MVC Controller Edit Server interface Edit Yesod uses a Web application interface API 4 abbreviated WAI to isolate servlets aka web apps from servers with handlers for the server protocols CGI 5 FastCGI 6 SCGI 7 Warp 8 Launch open as local URL to the default browser closing the server when the window is closed 9 The foundation type Edit See ref 10 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 like HomeR 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 e g web resource names and handler names By inserting a mkYesod call this will call Template Haskell primitives to generate the code 11 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 Edit Hello world example based on a CGI server interface The actual handler types have changed but the philosophy remains file wai cgi hello hs LANGUAGE PackageImports TypeFamilies QuasiQuotes MultiParamTypeClasses TemplateHaskell OverloadedStrings import wai Network Wai import wai extra Network Wai Handler CGI run interchangeable WAI handler import yesod Yesod import yesod core Yesod Handler getRequest import text Data Text Text import shakespeare Text Cassius Color colorBlack 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 parseRoutes HomeR GET instance Yesod MyApp indentation structured CSS template myStyle Text CssUrl url myStyle paramStyle cassius box border 1 px solid boxColor where boxColor case paramStyle of high contrast colorBlack Color 0 0 255 indentation structured HTML template myHtml Text Text HtmlUrl url myHtml params hamlet lt indentation or lack of it under starting tags or commands prefix describe the content or sequence tree structure gt lt or prefixes in tags introduce css styled class or id attribute values gt lt interpolation of haskell expressions follow the shakespeare templates expr syntax gt lt p gt Hello World There are lt span box gt length params parameters lt span gt if null params lt p gt Nothing to list else lt ul gt forall param lt params lt li gt fst param snd param getHomeR Handler RepHtml getHomeR do req lt getRequest let params reqGetParams req paramStyle lt lookupGetParams style defaultLayout do adding widgets to the Widget monad a Writer monad setTitle Yesod example toWidgetHead myStyle paramStyle toWidgetBody myHtml params there are run function variants for different WAI handlers main toWaiApp MyApp gt gt run cgi test export REMOTE ADDR 127 0 0 1 export REQUEST METHOD GET export PATH INFO export QUERY STRING p1 abc p2 def style high contrast wai cgi hello 10 Resources routes and HTTP method handlers Edit See ref 12 13 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 for example HomeR 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 parseRoutes HomeR no http methods stated all methods accepted blog BlogR GET POST the prefix specify the path segment as a route handler parameter article ArticleId ArticleR GET PUT the prefix specify the parameter as a sequence of path pieces branch Texts BranchR GET to simplify the grammar compound types must use an alias eg type Texts for Text Applying the previous template generates the following route constructors data Route MyApp HomeR referenced in templates as HomeR BlogR in templates BlogR ArticleR ArticleId in templates ArticleR myArticleId BranchR Texts in templates BranchR myBranchSegments 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 or the prefix handler if no method stated to the resource as described actual versions handler types have changed but the philosophy remains 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 Edit See ref 12 Authentication and authorization Edit See ref 14 Authentication plugins OpenId BrowserId Email GoogleEmail HashDB RpxNow 15 There is an important setting for automatic redirection after authentication 16 Sessions Edit See ref 17 Session back ends ClientSession 18 it stores the session in a cookie ServerSession 19 20 it stores most of the session data at the server gt gt To avoid undue bandwidth overhead production sites can serve their static content from a separate domain name to avoid the overhead of transmitting the session cookie for each requestSession messages Edit A success failure or indicative message can be stored setMessage in the Session and will be shown if it exists by the default layout routine through the default layout hamlet template being cleared on consultation 21 Subsites Edit Common URL prefix subsites for workflows file serving or site partitioning See ref 22 23 Built in subsites Static 24 25 Auth 26 Form processing and layout generation Edit See ref 27 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 FormResult Widget 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 with tabular layout Monadic with free layout style both in the Yesod Form Functions module Input for parsing only no view generated in the Yesod Form Input module The field generators whose names are composed by the form type initial a m i followed by req opt required or optional have a fieldParse component and a fieldView one 28 the function runForm Post Get runs the field parsers against the form field inputs and generates a FormResult Widget 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 Post Get ignores inputs from the client and generates a blank or defaults form widget 29 The actual function parameters and types have changed through Yesod versions Check the Yesod book and libraries signatures The magic is in the FormResult data type Applicative instance where lt gt collects the error messages for the case of FormFailure textErrMsg result values 30 Monadic forms permit free form layout and better treatment of hiddenField members 27 A sample of an Applicative 31 form a record for our form fields data Person Person personName Text personAge Int personLikings Maybe Text 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 FormResult x Widget for messages in validation functions param master yesod instance to use in renderMessage return from handler s getYesod param languages page languages to use in renderMessage optional defaults record param mbPersonDefaults Just defaults record or Nothing for blank form personForm MyFoundationType Text Maybe Person Form sub master Person aopt optional field AForm component for Maybe fields areq required fld AForm comp will insert the required attribute personForm master languages mbPersonDefaults renderTable Person lt gt areq textField fldSettingsName mbNameDefault lt gt areq customPersonAgeField fldSettingsAge mbAgeDefault lt gt 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 fieldSettingsLabel MsgName fsAttrs maxlength 20 fldSettingsAge fieldSettingsLabel MsgAge fldSettingsLikings fieldSettingsLabel MsgLikings fsAttrs cols 40 rows 10 customPersonAgeField check validateAge intField validateAge y y lt 18 Left renderMessage master languages MsgUnderAge otherwise Right y View Edit 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 32 RepHtml RepJson RepXml RepPlain the dual RepHtmlJson a pair or list of pairs ContentType Content 33 34 Json examples 35 36 37 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 32 Widgets 38 are HTML DOM code snippets made by specific commands e g setTitle or from templates of structure html behaviour JavaScript style css whose types instantiate the classes ToWidget ToWidgetHead or ToWidgetBody A Widget monad 39 based on a Writer 40 one and argument to defaultLayout facilitate to piece the widgets together Indentation based templates for tree structured markup Edit the hamlet quasiquoter a parser to compile time Template Haskell code 2 41 specified in the T H Oxford brackets syntax qq introduces an indentation based structured html template See doc 42 43 prefixes lines of logic statements Automatic closing tags are generated only for the tag at line start position the whamlet quasiquoter returns a Widget expression saves to Widget before hamlet toWidget hamlet doctype 5 lt html gt lt only the tag at the beginning of the line will be automatically closed gt lt or prefixes in tags introduce class id names a la CSS gt lt boolVar prefix in attributes makes them conditionally generated gt lt interpolation of haskell expressions follow the shakespearean templates syntax introduced in the so named section gt lt head gt lt title gt pageTitle My Site lt link rel stylesheet href Stylesheet route gt lt body gt lt header gt headerTemplate lt section mySectionId gt lt p gt lt span titleClass gt MsgArticleListTitle lt span gt if null articles lt p isRed style color red gt MsgSorryNoArticles else lt ul gt forall art lt articles lt li gt articleNumber art articleTitle art lt footer gt footerTemplate Template interpolation Shakespearean templates Edit See ref 42 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 template params route expressions with safe typed urls as HomeR message expressions with i18n message rendering as MsgMessageLabel params other Haskell expressions with haskell expression rendering as haskell expression which type must be convertiblein case of hamlet html templates the expression type must be an instance of Text Blaze ToMarkup 44 in case of css templates the expression type must be an instance of Text Cassius ToCss 45 in case of JavaScript templates the expression type must be an instance of Text Julius ToJavascript 46 in case of i18n message definitions in lt isoLanguage gt msg files with parameter interpolations the expression type must be an instance of Text Shakespeare I18N ToMessage 47 in case of text plain templates for use in emails the expression type must be an instance of Text Shakespeare Text ToText 48 Using non English text in expressions requires use of the Unicode aware type Text since GHC s show for the type String renders non ASCII characters as escaped numerical codes External file templatesat compile time Template content can be loaded from external files using compile time splice calls as expr 49 at run time There is a reload mode for reparsing external template files at every service call except for HTML hamlet templates See doc 50 Other templates Edit for JavaScript CoffeeScript Roy the julius quasiquoter introduces a JavaScript template 51 JavaScript variants CoffeeScript and Roy language 52 have also specific quasiquoters 2 51 for CSSthe cassius quasiquoter introduces a css template with indentation based structuring 53 the lucius quasiquoter introduces a css template with standard syntax plus shakespeare template style substitutions 54 TypeScript and JSX templates the tsc and tscJSX quasiquoters Only on UNIX derivatives no Windows by now 55 text plain templates for e mail or text plain http content type 56 templates lt lazy text st strict text templates for text with a left margin delimiter lbt lazy sbt strict Localizable messages Edit See ref 57 Yesod app messages are localizable i18n They should be held within the messages folder in files named based on ISO as lt iso language gt msg Message entries follow the EBNF pattern EBNF identifier parameter type text with interpolations ArticleUnexistent param Int64 unexistent article param 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 MsgArticleUnexistent myArticleId 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 58 Navigation Breadcrumbs Edit Navigation Breadcrumbs 59 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 route title pairs Search engine XML Sitemap Edit Search engines XML Sitemaps 60 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 Edit Web feed views RSS Atom 61 You have handlers that return RepRss RepAtom or dual RepAtomRss content to be selected on accept headers preferred content type list from a given Feed structure Model Edit Using in memory mutable data in the foundation datatype Edit E g a visitor count See ref 62 The Database layer Edit persistent is the name of the database access layer with templates for generating types for entities and keys as well as schema initialization 63 64 65 There is first class support for PostgreSQL SQLite MongoDB CouchDB and MySQL with experimental support for Redis 63 The Database layout is described in a template listing the entities fields and constraints 66 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 constraintswithsql level notation 67 At most one cardinality has a special mechanism around the type Checkmark 68 Weak entities childs in life constrained owner child relationships have no special support for cascade delete triggers but there are functions to deleteCascade manually in the Database Persist Class module 69 automatic table creation schema update and table migration Modifications of the entities template produces an schema update with automatic table creation and migration for the DBMS s that support ALTER TABLE SQL commands in a migrateAll procedure generated from the template content See Migrations in ref 63 to look for migration aware DBMS share mkPersist sqlSettings mkMigrate migrateAll generates the migration procedure with the specified name persist 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 persistent 70 Example for persistent rawSQL and Esqueleto queries 71 E mail Edit The following packages are part of the yesod platform 72 email validate Validating an email address 73 mime mail Compose and send MIME email messages 74 Facebook Edit Useful glue functions between the fb library and Yesod 75 Development cycle EditNew Yesod apps are generated from the HaskellStack tool 76 templates replacing previous command yesod init Stack based app template names are prefixed by yesod as yesod minimal postgres sqlite mysql mongo 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 Edit The yesod helper tool 77 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 Edit See refs 78 79 80 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 keter version 0 1 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 81 Old documentation Nginx based 82 83 Integration with JavaScript generated from functional languages EditSee ref 84 85 86 See also Edit Free and open source software portal Snap web framework References Edit yesodweb yesod github com Retrieved 13 June 2020 a b c HaskellWiki QuasiQuotation Haskell org 2012 05 26 Retrieved 2012 10 23 Univ of Kent Comparing Dynamic and Static Language Approaches to Web Frameworks Yesod vs Ruby on Rails PDF Retrieved 2012 10 23 The wai package Hackage haskell org Retrieved 2012 10 23 The wai extra package with CGI WAI handler Hackage haskell org Retrieved 2012 10 23 The wai handler fastcgi package Hackage haskell org Retrieved 2012 10 23 The wai handler scgi package Hackage haskell org Retrieved 2012 10 23 The warp package Hackage haskell org Retrieved 2012 10 23 The wai handler launch package Hackage haskell org Retrieved 2012 10 23 a b book Basics Yesodweb com Retrieved 2012 10 23 The mkYesod code a b book Routing and Handlers Yesodweb com Retrieved 2012 10 23 Playing with Routes and Links FPComplete com 2012 10 17 Retrieved 2012 10 28 book Authentication and Authorization Yesodweb com Retrieved 2012 10 23 The yesod auth package Hackage haskell org Retrieved 2012 10 26 book Sessions See section Ultimate Destination Yesodweb com Retrieved 2012 11 17 Sessions Yesodweb com Retrieved 2012 10 23 Web ClientSession Hackage haskell org Retrieved 2012 10 25 ServerSession secure modular server side sessions Hackage haskell org Retrieved 2018 10 29 Web ServerSession Frontend Yesod Hackage haskell org Retrieved 2018 10 29 Session Messages Yesodweb com Retrieved 2018 10 23 Creating a Subsite Yesodweb com Retrieved 2012 10 25 Yesod and subsites a no brainer Monoid se 2012 08 22 Retrieved 2012 10 28 The Magic of Yesod part 2 See section Static Subsite Yesodweb com 2010 12 25 Retrieved 2012 10 25 The package yesod static Static Subsite Hackage haskell org Retrieved 2012 10 25 The package yesod auth Auth Subsite Hackage haskell org Retrieved 2012 10 25 a b book Forms Yesodweb com Retrieved 2012 10 23 Yesod Form Fields Hackage haskell org Retrieved 2012 10 23 Yesod Form Functions runFormPost Hackage haskell org Retrieved 2012 10 25 Yesod Form Types Hackage haskell org Retrieved 2012 10 23 HaskellWiki Applicative functor haskell org Retrieved 2012 10 24 a b The class HasReps Hackage haskell org Retrieved 2012 10 23 RESTful Content Yesodweb com Retrieved 2012 10 23 The class ToContent Hackage haskell org Retrieved 2012 10 23 More Client Side Yesod todo sample Yesodweb com 2012 04 23 Retrieved 2012 10 23 JSON Web Service Yesodweb com Retrieved 2012 10 23 The yesod json package Hackage haskell org Retrieved 2012 10 23 book Widgets Yesodweb com Retrieved 2012 10 23 The widget monad Hackage haskell org Retrieved 2012 10 23 The Writer monad Haskell org Retrieved 2012 10 23 Template Haskell Quasi quotation Haskell org Retrieved 2012 11 02 a b book Shakesperean templates Yesodweb com Retrieved 2012 10 23 The hamlet template module Hackage haskell org Retrieved 2012 10 23 Class Text Blaze ToMarkup Hackage haskell org Retrieved 2012 10 23 Class Text Cassius ToCss Hackage haskell org Retrieved 2012 10 23 Class Text Julius ToJavascript Hackage haskell org Retrieved 2012 10 23 Class Text Shakespeare I18N ToMessage Hackage haskell org Retrieved 2012 10 24 Class Text Shakespeare Text ToText Hackage haskell org Retrieved 2012 10 24 Template Haskell haskell org Retrieved 2012 11 03 book Shakesperean templates Calling shakespeare Yesodweb com Retrieved 2012 10 23 a b The Julius template module Hackage haskell org Retrieved 2012 10 23 Roy language Roy brianmckenna org Retrieved 2012 10 23 The Cassius template module Hackage haskell org Retrieved 2012 10 23 The Lucius template module Hackage haskell org Retrieved 2012 10 23 The Typescript template module Hackage haskell org Retrieved 2018 10 10 Shakespeare plain text templates module Hackage haskell org Retrieved 2012 10 24 book Internationalization Yesodweb com Retrieved 2012 10 23 mkMessage The YesodBreadcrumbs class Hackage haskell org Retrieved 2012 11 05 The yesod sitemap package Hackage haskell org Retrieved 2012 10 26 The yesod newsfeed package for RSS Atom views Hackage haskell org Retrieved 2012 10 26 Book Initializing data in the foundation datatype Yesodweb com Retrieved 2014 05 26 a b c book Persistent Yesodweb com Retrieved 2012 10 23 Yesod persistent package Hackage haskell org Retrieved 2012 10 23 Yesod persistent docs github com Retrieved 2018 10 16 Yesod persistent entity syntax github com Retrieved 2018 10 16 Redundant migrations for fields default values GitHub com Retrieved 2012 12 04 At most one cardinality enforcement in persistent with type Checkmark Hackage haskell org Retrieved 2018 10 16 How can I create a foreign key constraint using Yesod Persistent stackoverflow com Retrieved 2018 10 16 esqueleto package Hackage haskell org Retrieved 2012 10 23 Query example at Stackoverflow com 2012 09 19 Retrieved 2012 10 23 The yesod package Hackage haskell org Retrieved 2019 06 26 The email validate package Hackage haskell org Retrieved 2012 10 26 The mime mail package Hackage haskell org Retrieved 2012 10 26 The yesod fb package Hackage haskell org Retrieved 2012 10 26 Haskell Stack How to install The yesod bin pkg with the helper tool with instructions for use with the stack tool book Deploying your Webapp Yesodweb com Retrieved 2012 10 23 Readme Md Yesod keter readme GitHub Retrieved 2012 10 23 The keter package Hackage haskell org Retrieved 2012 10 23 Keter updates Yesodweb com 2012 10 25 Retrieved 2012 10 25 Keter Web App Deployment Yesodweb com 2012 05 11 Retrieved 2012 10 23 Keter It s Alive Yesodweb com 2012 05 17 Retrieved 2012 10 23 Javascript Options github com Retrieved 2014 03 12 Yesod AngularJS and Fay yesodweb com 2012 10 30 Retrieved 2014 03 12 HaskellWiki The JavaScript Problem haskell org Retrieved 2014 04 12 External links EditOfficial website Presentations InfoQ Haskell eXchange 2012 Slides A C M at Johns Hopkins Univ ReST ful Websites with Yesod ScreenCast Yesod 1 0 at Vimeo O Reilly ebook Developing Web Applications with Haskell and Yesod Safety Driven Web Development Q amp A StackOverflow com Yesod tagged Q amp ABlog tutorials Edit FPComplete com My First Web Site Playing with Routes and Links Yesod for newbies hamberg no handlerToIO use forkIO in Yesod handlersComparisons Edit HaskellWiki Haskell web frameworks A Hopefully Fair and Useful Comparison of Haskell Web Frameworks Univ of Kent Comparing Dynamic and Static Language Approaches to Web Frameworks Yesod vs Ruby on RailsOther languages Edit Haskell Biblio Yesod in Spanish Univ of CadizAt Linux distributions Edit Yesod at Debian Yesod at Ubuntu Retrieved from https en wikipedia org w index php title Yesod web framework amp oldid 1036339119, wikipedia, wiki, book,

books

, library,

article

, read, download, free, free download, mp3, video, mp4, 3gp, jpg, jpeg, gif, png, picture, music, song, movie, book, game, games.