1 module temple.vibe;
2 
3 version(Have_vibe_d):
4 
5 pragma(msg, "Compiling Temple with Vibed support");
6 
7 private {
8 	import temple;
9 	import vibe.http.server;
10 	import vibe.textfilter.html;
11 	import std.stdio;
12 }
13 
14 struct TempleHtmlFilter {
15 
16 	private static struct SafeString {
17 		const string payload;
18 	}
19 
20 	static void temple_filter(ref TempleOutputStream stream, string unsafe) {
21 		filterHTMLEscape(stream, unsafe);
22 	}
23 
24 	static string temple_filter(SafeString safe) {
25 		return safe.payload;
26 	}
27 
28 	static SafeString safe(string str) {
29 		return SafeString(str);
30 	}
31 }
32 
33 private enum SetupContext = q{
34 	static if(is(Ctx == HTTPServerRequest)) {
35 		TempleContext context = new TempleContext();
36 		copyContextParams(context, req);
37 	}
38 	else {
39 		TempleContext context = req;
40 	}
41 };
42 
43 private template isSupportedCtx(Ctx) {
44 	enum isSupportedCtx = is(Ctx : HTTPServerRequest) || is(Ctx == TempleContext);
45 }
46 
47 void renderTemple(string temple, Ctx = TempleContext)
48 	(HTTPServerResponse res, Ctx req = null)
49 	if(isSupportedCtx!Ctx)
50 {
51 	mixin(SetupContext);
52 
53 	auto t = Temple!(temple, TempleHtmlFilter);
54 	t.render(res.bodyWriter, context);
55 }
56 
57 void renderTempleFile(string file, Ctx = TempleContext)
58 	(HTTPServerResponse res, Ctx req = null)
59 	if(isSupportedCtx!Ctx)
60 {
61 	mixin(SetupContext);
62 
63 	alias render = compile_temple_file!(file, TempleHtmlFilter);
64 	render(res.bodyWriter, context);
65 }
66 
67 void renderTempleLayoutFile(string layout_file, string partial_file, Ctx = TempleContext)
68 	(HTTPServerResponse res, Ctx req = null)
69 	if(isSupportedCtx!Ctx)
70 {
71 	mixin(SetupContext);
72 
73 	alias layout = TempleLayoutFile!(layout_file, TempleHtmlFilter);
74 	alias partial = compile_temple_file!(partial_file, TempleHtmlFilter);
75 
76 	layout(res.bodyWriter, &partial, context);
77 }
78 
79 private void copyContextParams(ref TempleContext ctx, ref HTTPServerRequest req) {
80 
81 	if(!req || !(req.params))
82 		return;
83 
84 	foreach(key, val; req.params) {
85 		ctx[key] = val;
86 	}
87 }