◊require in templates
#65
Closed
opened 10 years ago by kirelagin
·
3 comments
Loading…
Reference in New Issue
There is no content yet.
Delete Branch '%!s(<nil>)'
Deleting a branch is permanent. It CANNOT be undone. Continue?
I’m stuck with a very dumb question. I can’t figure out how to
require
something in a template.For example, I want to use
xexpr->string
instead of->html
, so I neeed a way to◊(require xml)
, however:gives me:
In the future, I will want to use even more complex functions, potentially
require
d from other packages. So what is the recommended way to do this?Not a dumb question, and I don’t think I cover it in the docs (though this is the sign I should).
As the error indicates,
require
has to be at the top level of the source file being evaluated. A template, however, is a code fragment that’s being pulled into that source file dynamically. (You’ve noticed that unlike other files in Pollen, a template doesn’t start with#lang pollen
— because it’s not a standalone source file.) So a template can never userequire
, because it can’t reach the top level of the source file.You have two options instead:
local-require
, which is basically the same asrequire
(= imports identifiers into the namespace) but can be used in positions other than the top level.dynamic-require
, which is a form ofrequire
that can be used at runtime. Unlikerequire
andlocal-require
, the identifiers are passed as quoted-symbol arguments. Rather than importing identifiers,dynamic-require
returns the value of the requested identifier. In this case, you get a function:In HTML templates, you’ll probably want to use
local-require
.Cool, thanks.
I wonder, what is that local context that the name I
local-require
in a template gets imported into. In other words, in what other unexpected places can this name potentially emerge?The scope of
local-require
is the lexical context where it’s used. (This almost means the expression where it’s used, but not quite, because some expressions (likebegin
) don’t create their own lexical context.)In practice, the
local-require
s in a template don’t carry a risk of emerging elsewhere. Pollen renders a template by pulling it into a dynamically-generated lexical context that consists of a) the template code and b) the exports of the markup file (=metas
,doc
,here
).That said, I don’t find Racket’s approach to templates entirely satisfying. It would be more consistent to have
template.html
be a#lang pollen
source file that can be independently tested and run.