33 using System ;
44 using System . Collections . Generic ;
55 using System . IO ;
6+ using System . Linq ;
67 using Microsoft . AspNetCore . Hosting ;
78 using Microsoft . AspNetCore . Http ;
89
910 public class DefaultViewLocator : IViewLocator
1011 {
12+ private readonly HtmlNegotiatorOptions options ;
1113 private readonly IDictionary < Type , string > mappings ;
1214
1315 private readonly IDictionary < Type , string > htmlMappings ;
1416
15- public DefaultViewLocator ( IDictionary < Type , string > mappings )
17+ public DefaultViewLocator ( HtmlNegotiatorOptions options )
1618 {
17- this . mappings = mappings ;
19+ this . options = options ;
20+ this . mappings = new Dictionary < Type , string > ( ) ;
1821 this . htmlMappings = new Dictionary < Type , string > ( ) ;
1922 }
2023
2124 public string GetView ( object model , HttpContext httpContext )
2225 {
23- string viewName = string . Empty ;
24- try
25- {
26- viewName = this . mappings [ model . GetType ( ) ] ;
27- }
28- catch ( Exception )
29- {
30- return string . Empty ;
31- }
26+ string viewName = httpContext . Items . ContainsKey ( "View" ) ? httpContext . Items [ "View" ] . ToString ( ) : "index.hbs" ;
27+ string moduleName = "home" ;
3228
3329 if ( this . htmlMappings . ContainsKey ( model . GetType ( ) ) )
3430 {
@@ -37,10 +33,26 @@ public string GetView(object model, HttpContext httpContext)
3733
3834 var env = ( IHostingEnvironment ) httpContext . RequestServices . GetService ( typeof ( IHostingEnvironment ) ) ;
3935
40- try
36+ if ( httpContext . Items . ContainsKey ( "ModuleType" ) )
4137 {
42- var html = File . ReadAllText ( Path . Combine ( env . ContentRootPath , viewName ) ) ;
38+ var moduleType = httpContext . Items [ "ModuleType" ] as Type ;
39+ if ( mappings . ContainsKey ( moduleType ) )
40+ {
41+ moduleName = mappings [ moduleType ] ;
42+ }
43+ else
44+ {
45+ var moduleTypeName = moduleType . ToString ( ) . Split ( '.' ) . Last ( ) . ToLower ( ) ;
46+ moduleName = moduleTypeName . Substring ( 0 , moduleTypeName . IndexOf ( "module" ) ) ;
47+ mappings . Add ( moduleType , moduleName ) ;
48+ }
49+ }
4350
51+ try
52+ {
53+ var path = Path . Combine ( env . ContentRootPath , options . ViewLocation , moduleName , viewName ) ;
54+ path = Path . GetExtension ( path ) == ".hbs" ? path : $ "{ path } .hbs";
55+ var html = File . ReadAllText ( path ) ;
4456 this . htmlMappings . Add ( model . GetType ( ) , html ) ;
4557
4658 return html ;
0 commit comments