Skip to content

Instantly share code, notes, and snippets.

@srid
Created March 26, 2021 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srid/645fcc6363852e7617c4fd356463860a to your computer and use it in GitHub Desktop.
Save srid/645fcc6363852e7617c4fd356463860a to your computer and use it in GitHub Desktop.
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