From afc4b923cc800d421252dfe72ab112632e05bf7a Mon Sep 17 00:00:00 2001 From: Ody Mbegbu Date: Wed, 11 Apr 2018 09:03:12 +0100 Subject: [PATCH] Add folder support to Razor View Search --- src/Giraffe.Razor/RazorEngine.fs | 39 ++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/src/Giraffe.Razor/RazorEngine.fs b/src/Giraffe.Razor/RazorEngine.fs index 284388e..fa0be2e 100644 --- a/src/Giraffe.Razor/RazorEngine.fs +++ b/src/Giraffe.Razor/RazorEngine.fs @@ -15,20 +15,51 @@ module RazorEngine = open FSharp.Control.Tasks.ContextInsensitive open Giraffe + let private extractRouteData (path:string) = + + let templatePath = path + "" //Normalize nulls + + //Split path into segments and reverse the orders + let segments = + templatePath.Split('/', '\\') + |> List.ofSeq + |> List.rev + + let routeValues = + seq { + for i in 1..segments.Length do + match i with + | 1 -> yield "action", segments.[0] + | 2 -> yield "controller", segments.[1] + | 3 -> yield "area", segments.[2] + | x -> yield sprintf "token-%d" (x), segments.[x - 1] + } + + //Create RouteData Object using Values Created + let routeData = RouteData() + + for (key,value) in routeValues do + routeData.Values.Add(key, value) + + routeData + let renderView (razorViewEngine : IRazorViewEngine) (tempDataProvider : ITempDataProvider) (httpContext : HttpContext) (viewName : string) (model : 'T) = task { - let actionContext = ActionContext(httpContext, RouteData(), ActionDescriptor()) - let viewEngineResult = razorViewEngine.FindView(actionContext, viewName, true) + let routeData = extractRouteData(viewName) + let templateName = routeData.Values.["action"].ToString() + + let actionContext = ActionContext(httpContext, routeData, ActionDescriptor()) + let viewEngineResult = razorViewEngine.FindView(actionContext, templateName, true) match viewEngineResult.Success with | false -> let locations = String.Join(" ", viewEngineResult.SearchedLocations) - return Error (sprintf "Could not find view with the name '%s'. Looked in %s." viewName locations) - | true -> + return Error (sprintf "Could not find view with the name '%s'. Looked in %s." templateName locations) + | true -> let view = viewEngineResult.View let viewDataDict = ViewDataDictionary<'T>(EmptyModelMetadataProvider(), ModelStateDictionary(), Model = model) let tempDataDict = TempDataDictionary(actionContext.HttpContext, tempDataProvider)