Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hamlet automatic access to variables in scope

From the Yesod Book.

Hamlet automatically has access to the variables in scope when it's called. There is no need to specifically pass variables in.

What is this deep magic? How can it automagically know what variables are in scope?

like image 882
Dan Burton Avatar asked Feb 01 '12 07:02

Dan Burton


1 Answers

Hamlet is based on Template Haskell; in particular, a quasiquoter (i.e. [hamlet| ... |]) is used for inline templates, and a splice (i.e. $(hamletFile "foo")) is used to create templates from a file. The variables are then accessed with Template Haskell's introspection features.

This has benefits beyond allowing automatic access to variables:

  • The resulting templates are likely more efficient than ones parsed and interpreted at runtime, since Hamlet templates are compiled to regular Haskell code at compile-time.

  • When reading a template from a file, the file is parsed at compile-time and embedded into the resulting binary, so the templates don't have to be kept around in the same location at runtime, and the validity of templates is ensured statically.

I believe these advantages apply to all Shakespeare-family templates. The Haddock documentation has more information on the available quasiquoters and splices.

like image 107
ehird Avatar answered Sep 28 '22 15:09

ehird