[erlang-questions] [ANN] Brim - HTML templating library
Richard O'Keefe
ok@REDACTED
Thu Mar 15 21:57:37 CET 2012
Just for grins, let's look at another way of doing it,
using another programming language.
On 16/03/2012, at 1:17 AM, Michael Turner wrote:
> <html><head><title>The title</title></head><body>The body</body></html>
Change it to
<html>
<head>
<title><span class="C:replace">TITLE</span></title>
</head>
<body>
<p><span class="C:replace">BODY</span></p>
</body>
</html>
% qh -hew sample.xml | page-gen >sample.c
% cat sample.c
#include "dvm2.h"
extern void replace(xml);
void generate(xml e) {
x_begin("html");
x_begin("head");
x_begin("title");
x_begin("span");
x_pcdata("TITLE");
x_end("span");
replace(x_pop());
x_end("title");
x_end("head");
x_begin("body");
x_begin("p");
x_begin("span");
x_pcdata("BODY");
x_end("span");
replace(x_pop());
x_end("p");
x_end("body");
x_end("html");
}
#ifdef TEST
int main(void) {
generate(pcdata_str(""));
write_xml(stdout, "", x_pop(), XML_SHOW_HTML|XML_SHOW_LATIN1);
return 0;
}
#endif/*TEST*/
Now plug in a definition:
void replace(xml e) {
char const *k = text_of(pcdata_text(e));
if (0 == strcmp(k, "TITLE")) {
x_pcdata("The title");
} else
if (0 == strcmp(k, "BODY")) {
x_pcdata("The body");
} else {
x_begin1("font", "color", "red");
x_pcdata("No value known for: ");
x_push(e);
x_end("font");
}
}
and you're away laughing.
The idea here is that the input is turned into C code that
will reproduce it, except that elements with the attribute
class = "C:<<function>>" will be handed to the function of
the given name for processing. The Erlang version would
translate
<html>
<head>
<title><span class="E:mod:replace">TITLE</span></title>
</head>
<body>
<p><span class="E:mod:replace">BODY</span></p>
</body>
</html>
to
f() ->
{html,[],[
{head,[],[
{title,[],[
]++mod:replace({span,[],[<<"TITLE">>]})++[
]}]},
{body,[],[
{p,[],[
]++mod:replace({span,[],[<<"BODY">>]})++[
]}]}]).
This kind of stuff is _so_ easy to do... (The C example is real;
the Erlang one is not.)
More information about the erlang-questions
mailing list