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();
}


// 用法

//也可这样:import("file.html")导入
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;
    //在<% %> 块中可看见.
    string my_string = "你好.世界";
	string[] strings = ["omg", "wtf", "lol"];
	void append(string s) {
		html ~= s;
	}
	mixin(loadTemplateMixin!doc);
	import std.stdio;
	writeln(html);
}