vibe.d: is it possible to use bare HTML with the functionalty of DIET templates ?
Adam D Ruppe
destructionator at gmail.com
Tue Aug 31 02:17:49 UTC 2021
On Tuesday, 31 August 2021 at 00:09:14 UTC, someone wrote:
> Can I use vibe.d *without* DIET templates manually writing say,
> XHTML 1.1 pages, *while having D* at my disposal with the -
> prefixes I have seen so far ?
I don't know much about vibe.d (I have my own D web stuff) but
just for fun I wanted to try passing my dom.d through the ctfe
engine to do the embedded code thing.
50ish lines for the basic extractor i slapped together in 20 mins.
---
import arsd.dom;
string toD(string s) {
return `append(` ~ "`" ~ s ~ "`" ~ `);`;
}
template loadTemplateMixin(string doc) {
string helper() {
Document document = new Document;
document.parseSawAspCode = (string) => true;
document.parseStrict(doc);
string code;
void expand(Element element) {
if(auto asp = cast(AspCode) element) {
if(asp.source.length > 3 && asp.source[1] == '=')
code ~= `append(` ~ asp.source[2 .. $-1] ~ `);`;
else
code ~= asp.source[1 .. $-1];
} else if(auto tn = cast(TextNode) element) {
code ~= toD(tn.toString());
} else if(auto sn = cast(SpecialElement) element) {
code ~= toD(sn.toString());
} else {
code ~= toD("<" ~ element.tagName);
foreach(k, v; element.attributes) {
code ~= toD(" ");
code ~= toD(k.htmlEntitiesEncode);
code ~= toD("=\"");
code ~= toD(v.htmlEntitiesEncode);
code ~= toD("\"");
}
code ~= toD(">");
foreach(child; element.children)
expand(child);
code ~= toD("</" ~ element.tagName ~ ">");
}
}
expand(document.root);
return code;
}
enum loadTemplateMixin = helper();
}
// USAGE HERE
// this could be in a file import("file.html") too btw
enum doc = `<html><script> foo</script><style>css</style><test
id="main"><%= my_string[0 .. 5] %></test>
<span>foo</span>
<span>foo</span>
<span>foo</span>
<% foreach(item; strings)
append(item);
%>
</html>`;
void main() {
string html;
// and it can see these variables in the <% %> blocks
string my_string = "hello world";
string[] strings = ["omg", "wtf", "lol"];
void append(string s) {
html ~= s;
}
mixin(loadTemplateMixin!doc);
import std.stdio;
writeln(html);
}
---
Not exactly the fastest compile though but I could prolly
optimize that if i spent a lil more time on it.
Now that it yields a string though you can return that to vibe
using whatever method it uses.
Also note that you get a compile error on malformed input xhtml
too.
More information about the Digitalmars-d-learn
mailing list