1 /**
2 * Copyright © DiamondMVC 2018
3 * License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 */
6 module diamond.views.viewroute;
7 
8 import diamond.core.apptype;
9 
10 static if (!isWebApi)
11 {
12   /// Mixin template for generating the getView() function.
13   mixin template GenerateGetView()
14   {
15     import diamond.core.apptype;
16     import std..string : format;
17     import diamondapp;
18 
19     static if (isWebServer)
20     {
21       import diamond.http;
22 
23       /**
24       * Generates the getView() function.
25       * Returns:
26       *   The resulting string of the getView() function to use in a mixin.
27       */
28       string generateGetView()
29       {
30         string getViewMixin = "
31           View getView(HttpClient client, Route route, bool checkRoute, bool keepRoute = false)
32           {
33             auto viewName =
34               routableViews.get(route.name, checkRoute ? null : route.name);
35 
36             if (!viewName)
37             {
38               return null;
39             }
40 
41             switch (viewName)
42             {
43         ";
44 
45         mixin LoadViewData!true;
46 
47         foreach (viewName; getViewData().keys)
48         {
49           getViewMixin ~= format(q{
50             case "%s":
51             {
52               if (!keepRoute)
53               {
54                 client.route = route;
55               }
56 
57               return new view_%s(client, "%s");
58             }
59           }, viewName, viewName, viewName);
60         }
61 
62         getViewMixin ~= "
63               default: return null; // 404 ...
64             }
65           }
66         ";
67 
68         return getViewMixin;
69       }
70     }
71     else
72     {
73       /**
74       * Generates the getView() function.
75       * Returns:
76       *   The resulting string of the getView() function to use in a mixin.
77       */
78       string generateGetView()
79       {
80         string getViewMixin = "
81           View getView(string viewName)
82           {
83             if (!viewName || !viewName.length)
84             {
85               return null;
86             }
87 
88             switch (viewName)
89             {
90         ";
91 
92         mixin LoadViewData!true;
93 
94         foreach (viewName; getViewData().keys)
95         {
96           getViewMixin ~= format(q{
97             case "%s":
98             {
99               return new view_%s("%s");
100             }
101           }, viewName, viewName, viewName);
102         }
103 
104         getViewMixin ~= "
105               default: return null; // 404 ...
106             }
107           }
108         ";
109 
110         return getViewMixin;
111       }
112     }
113 
114     mixin(generateGetView);
115   }
116 }