MVC architecture
Controller
Server interface
Yesod uses a ''Web application interface'' API, abbreviated ''WAI'', to isolateThe ''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". TheHello World
"Hello world" example based on a CGI server interface (The actual handler types have changed, but the philosophy remains):Hello World! There are # parameters: $if null params
Nothing to list $else
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.Request data, Parameters, Cookies, Languages and other Header info
See ref.Authentication and authorization
See ref. Authentication plugins: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 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, AuthForm 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)
, have a fieldParse component and a fieldView one.
*the function runForm
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
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 data type Applicative instance, where collects the error messages for the case of FormFailure extErrMsg/code> result values
Monadic forms permit free form layout and better treatment of 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 (FormResult x, Widget)
personForm :: MyFoundationType → ext
Ext, ext or EXT may refer to:
* Ext functor, used in the mathematical field of homological algebra
* Ext (JavaScript library), a programming library used to build interactive web applications
* Exeter Airport (IATA airport code), in Devon, Engla ...
→ 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 = (fieldSettingsLabel MsgName)
fldSettingsAge = fieldSettingsLabel MsgAge
fldSettingsLikings = (fieldSettingsLabel MsgLikings)
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 class . Json examples:
The default implementation of chooses the document representation to be returned according to the preferred content-type list of the client header.
* Widgets are HTML
The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScri ...
DOM code snippets made by specific commands (e.g. setTitle) or from templates of structure (HTML
The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScri ...
) / behaviour (JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
) / style (CSS
Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a document written in a markup language such as HTML or XML (including XML dialects such as SVG, MathML or XHTML). CSS is a cornerstone t ...
), whose types instantiate the classes ToWidget, ToWidgetHead or ToWidgetBody.
A Widget monad, based on a Writer one and argument to , facilitate to piece the widgets together.
Indentation based templates for tree structured markup
* the quasiquoter (a parser to compile-time Template Haskell code) specified in the T.H. Oxford brackets syntax ... , /code> 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 quasiquoter returns a Widget expression. (saves to Widget before .., .
toWidget [hamlet,
$doctype 5
# - My Site
^
_
$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 (typed) 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
''The Tragedy of Hamlet, Prince of Denmark'', often shortened to ''Hamlet'' (), is a tragedy written by William Shakespeare sometime between 1599 and 1601. It is Shakespeare's longest play, with 29,551 words. Set in Denmark, the play depi ...
'' html templates, the expression type must be an instance of Text.Blaze.ToMarkup
** in case of CSS
Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a document written in a markup language such as HTML or XML (including XML dialects such as SVG, MathML or XHTML). CSS is a cornerstone t ...
templates, the expression type must be an instance of Text.Cassius.ToCss
** in case of JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
templates, the expression type must be an instance of Text.Julius.ToJavascript
** in case of i18n message definitions (in "
.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
Unicode, formally The Unicode Standard,The formal version reference is is an information technology standard for the consistent encoding, representation, and handling of text expressed in most of the world's writing systems. The standard, ...
-aware type , since GHC's for the type renders non-ASCII
ASCII ( ), abbreviated from American Standard Code for Information Interchange, is a character encoding standard for electronic communication. ASCII codes represent text in computers, telecommunications equipment, and other devices. Because ...
characters as escaped numerical codes.
; External file templates:
* at compile time: Template content can be loaded from external files using compile time calls as ''$(expr)''.
* at run time: There is a ''reload mode'' for reparsing external template files at every service call, except for HTML templates: See doc.
= Other templates
=
; for JavaScript, CoffeeScript, Roy: the quasiquoter: introduces a JavaScript template. JavaScript variants CoffeeScript
CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehen ...
and Roy-language have also specific .
;for CSS:
* the quasiquoter: introduces a css template with indentation based structuring.
* the quasiquoter: introduces a css template with standard syntax plus shakespeare-template style substitutions.
; TypeScript
TypeScript is a free and open source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. It is designed for the development of large appl ...
and JSX templates: the and quasiquoters. Only on UNIX
Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, a ...
derivatives (no Windows
Windows is a group of several proprietary graphical operating system families developed and marketed by Microsoft. Each family caters to a certain sector of the computing industry. For example, Windows NT for consumers, Windows Server for ...
by now).
; text/plain templates: for e-mail
Electronic mail (email or e-mail) is a method of exchanging messages ("mail") between people using electronic devices. Email was thus conceived as the electronic ( digital) version of, or counterpart to, mail, at a time when "mail" mean ...
or ''text/plain''
content type.
#templates: : lazy text, : strict text
#templates for text with a left margin delimiter ', ': (lazy), (strict)
Localizable messages
See ref.
Yesod app messages are localizable ( i18n). They should be held within the 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 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
Bread crumbs or breadcrumbs (regional variants including breading and crispies) consist of crumbled bread of various dryness, sometimes with seasonings added, used for breading or crumbing foods, topping casseroles, stuffing poultry, thick ...
. You have to provide a YesodBreadcrumbs instance for the site where the generator function should return for each route a title and parent one. Then, the query function will return the present route title and the ancestors' (route, title) pairs.
Search engine XML Sitemap
* Search engines XML Sitemaps, where returns an XML Sitemap as
response, with the routes we want the search engines to crawl, and attributes to instruct the crawler, from a provided list of records.
Web feed views
* Web feed
On the World Wide Web, a web feed (or news feed) is a data format used for providing users with frequently updated content. Content distributors ''Web syndication, syndicate'' a web feed, thereby allowing users to ''subscribe'' a channel to it b ...
views (RSS
RSS ( RDF Site Summary or Really Simple Syndication) is a web feed that allows users and applications to access updates to websites in a standardized, computer-readable format. Subscribing to RSS feeds can allow a user to keep track of many di ...
/ Atom
Every atom is composed of a nucleus and one or more electrons bound to the nucleus. The nucleus is made of one or more protons and a number of neutrons. Only the most common variety of hydrogen has no neutrons.
Every solid, liquid, gas ...
). You have handlers that return , or dual content (to be selected on headers' preferred content-type list) from a given 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
PostgreSQL (, ), also known as Postgres, is a free and open-source relational database management system (RDBMS) emphasizing extensibility and SQL compliance. It was originally named POSTGRES, referring to its origins as a successor to the In ...
, SQLite
SQLite (, ) is a database engine written in the C programming language. It is not a standalone app; rather, it is a library that software developers embed in their apps. As such, it belongs to the family of embedded databases. It is the mo ...
, MongoDB
MongoDB is a source-available cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas. MongoDB is developed by MongoDB Inc. and licensed under the Ser ...
, CouchDB
Apache CouchDB is an open-source document-oriented NoSQL database, implemented in Erlang.
CouchDB uses multiple formats and protocols to store, transfer, and process its data. It uses JSON to store data, JavaScript as its query language using ...
and MySQL
MySQL () is an open-source relational database management system (RDBMS). Its name is a combination of "My", the name of co-founder Michael Widenius's daughter My, and "SQL", the acronym for Structured Query Language. A relational database ...
, with experimental support for Redis
Redis (; Remote Dictionary Server) is an in-memory data structure store, used as a distributed, in-memory key–value database, cache and message broker, with optional durability. Redis supports different kinds of abstract data structures, suc ...
.
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
In computing, a database is an organized collection of data stored and accessed electronically. Small databases can be stored on a file system, while large databases are hosted on computer clusters or cloud storage. The design of databases span ...
'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
In computing, a database is an organized collection of data stored and accessed electronically. Small databases can be stored on a file system, while large databases are hosted on computer clusters or cloud storage. The design of databases span ...
.
share kPersist 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''.
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
Multipurpose Internet Mail Extensions (MIME) is an Internet standard that extends the format of email messages to support text in character sets other than ASCII, as well as attachments of audio, video, images, and application programs. Messa ...
email messages.
Facebook
* Useful glue functions between the fb library and Yesod.
Development cycle
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-"
*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
PostgreSQL (, ), also known as Postgres, is a free and open-source relational database management system (RDBMS) emphasizing extensibility and SQL compliance. It was originally named POSTGRES, referring to its origins as a successor to the In ...
.
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
Nginx (pronounced "engine x" ) is a web server that can also be used as a reverse proxy, load balancer, mail proxy and HTTP cache. The software was created by Igor Sysoev and publicly released in 2004. Nginx is free and open-source software ...
as reverse proxy
In computer networks, a reverse proxy is the application that sits in front of back-end applications and forwards client (e.g. browser) requests to those applications. Reverse proxies help increase scalability, performance, resilience and securi ...
(keter version 0.1*), adding virtual server entries to its configuration and making Nginx
Nginx (pronounced "engine x" ) is a web server that can also be used as a reverse proxy, load balancer, mail proxy and HTTP cache. The software was created by Igor Sysoev and publicly released in 2004. Nginx is free and open-source software ...
reload it, but now Keter itself provides its own ''reverse proxy
In computer networks, a reverse proxy is the application that sits in front of back-end applications and forwards client (e.g. browser) requests to those applications. Reverse proxies help increase scalability, performance, resilience and securi ...
'' functionality, removing Nginx dependency and acting as the main web server.
Old documentation (Nginx based).
Integration with
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
generated from functional languages
See ref.
See also
* Snap (web framework)
References
External links
*
* 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&A
StackOverflow.com - Yesod tagged Q&A
Blog tutorials
FPComplete.com - My First Web Site
Playing with Routes and Links
Yesod for newbies
Comparisons
HaskellWiki - Haskell web frameworks
* ttp://www.cs.kent.ac.uk/~nccb/rails-yesod-slides.pdf Univ. of Kent - Comparing Dynamic and Static Language Approaches to Web Frameworks - Yesod vs Ruby on Rails
Other languages
Haskell Biblio. - Yesod
Univ. of Cadiz
At Linux distributions
Yesod at Debian
Yesod at Ubuntu
{{Web frameworks
Web frameworks
Free software programmed in Haskell
Haskell software