Created
March 26, 2021 23:00
-
-
Save srid/645fcc6363852e7617c4fd356463860a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Feather.Template | |
open System.IO | |
open System.Text | |
open Microsoft.AspNetCore.Http | |
open Microsoft.AspNetCore.Hosting | |
open Microsoft.Extensions.DependencyInjection | |
open DotLiquid | |
open Giraffe | |
open FSharp.Control.Tasks | |
open DotLiquid.FileSystems | |
module Fork = | |
/// Renders a model and a template with the DotLiquid template engine and sets the HTTP response | |
/// with the compiled output as well as the Content-Type HTTP header to the given value. | |
let dotLiquid (contentType : string) (template : string) (model : obj) : HttpHandler = | |
let view = Template.Parse template | |
let bytes = | |
model | |
|> Hash.FromAnonymousObject | |
|> view.Render | |
|> Encoding.UTF8.GetBytes | |
setHttpHeader "Content-Type" contentType | |
>=> setBody bytes | |
/// Reads a dotLiquid template file from disk and compiles it with the given model and sets | |
/// the compiled output as well as the given contentType as the HTTP response. | |
let dotLiquidTemplate (contentType : string) (templatePath : string) (model : obj) : HttpHandler = | |
fun (next : HttpFunc) (ctx : HttpContext) -> | |
task { | |
let env = ctx.RequestServices.GetService<IWebHostEnvironment>() | |
let path = Path.Combine(env.ContentRootPath, templatePath) | |
let! template = readFileAsStringAsync path | |
let env = ctx.RequestServices.GetService<IWebHostEnvironment>() | |
let templateFolder = Path.Combine(env.ContentRootPath, "templates") | |
Template.FileSystem <- LocalFileSystem(templateFolder) | |
return! dotLiquid contentType template model next ctx | |
} | |
/// Reads a dotLiquid template file from disk and compiles it with the given model and sets | |
/// the compiled output as the HTTP response with a Content-Type of text/html. | |
let dotLiquidHtmlTemplate (templatePath : string) (model : obj) : HttpHandler = | |
dotLiquidTemplate "text/html" templatePath model |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment