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?

有帮助吗?

解决方案

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.

其他提示

It's a feature of Haskell's quasiquotation, which is the [xxx| .... |] syntax.

The quasiquoter can access any variables that are in scope, so they can be interpolated. The actual implementation of interpolation (if any) depends on the quasiquoter itself.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top