문제

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