├── .gitattributes ├── tests ├── Giraffe.ViewEngine.Tests │ ├── xunit.runner.json │ ├── Giraffe.ViewEngine.Tests.fsproj │ └── Tests.fs └── Giraffe.ViewEngine.Benchmarks │ ├── README.txt │ ├── Giraffe.ViewEngine.Benchmarks.fsproj │ └── Program.fs ├── giraffe-64x64.png ├── samples └── Giraffe.ViewEngine.Sample │ ├── sample-screenshot.jpg │ ├── Giraffe.ViewEngine.Sample.fsproj │ └── Program.fs ├── NuGet.config ├── src └── Giraffe.ViewEngine │ ├── StringBuilderPool.fs │ ├── Giraffe.ViewEngine.fsproj │ └── Engine.fs ├── RELEASE_NOTES.md ├── .github └── workflows │ └── build.yml ├── CODE_OF_CONDUCT.md ├── Giraffe.ViewEngine.sln ├── .gitignore ├── LICENSE └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto 2 | *.sh text eol=lf -------------------------------------------------------------------------------- /tests/Giraffe.ViewEngine.Tests/xunit.runner.json: -------------------------------------------------------------------------------- 1 | { 2 | "appDomain": "denied" 3 | } -------------------------------------------------------------------------------- /giraffe-64x64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giraffe-fsharp/Giraffe.ViewEngine/master/giraffe-64x64.png -------------------------------------------------------------------------------- /samples/Giraffe.ViewEngine.Sample/sample-screenshot.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giraffe-fsharp/Giraffe.ViewEngine/master/samples/Giraffe.ViewEngine.Sample/sample-screenshot.jpg -------------------------------------------------------------------------------- /tests/Giraffe.ViewEngine.Benchmarks/README.txt: -------------------------------------------------------------------------------- 1 | When running the benchmarks with .NET Core >= 3.0, running Giraffe.ViewEngine.Benchmarks.exe will throw exceptions. 2 | 3 | Instead, call it via the .NET CLI, e.g.: `dotnet run Giraffe.ViewEngine.Benchmarks.dll` 4 | -------------------------------------------------------------------------------- /NuGet.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /samples/Giraffe.ViewEngine.Sample/Giraffe.ViewEngine.Sample.fsproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | GithubExample 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /tests/Giraffe.ViewEngine.Benchmarks/Giraffe.ViewEngine.Benchmarks.fsproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net6.0 4 | Exe 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /samples/Giraffe.ViewEngine.Sample/Program.fs: -------------------------------------------------------------------------------- 1 | module Sample = 2 | open Giraffe.ViewEngine 3 | 4 | let bodyTemplate (nameList: string list): XmlNode = 5 | body [] 6 | [ h1 [] [ Text "Welcome:" ] 7 | ol [] (nameList |> List.map (fun x -> li [] [ Text x ])) ] 8 | 9 | let navTemplate = 10 | nav [] [ a [ _href "./About" ] [ Text "About" ] ] 11 | 12 | let documentTemplate (nav: XmlNode) (body: XmlNode) = 13 | html [] [ nav; body ] 14 | 15 | let render welcomeUsers = 16 | bodyTemplate welcomeUsers 17 | |> (documentTemplate navTemplate) 18 | |> RenderView.AsString.htmlDocument 19 | 20 | [] 21 | let main args = 22 | let tfn = 23 | (System.IO.Path.GetTempFileName()) |> sprintf "%s.html" 24 | 25 | args 26 | |> Seq.toList 27 | |> Sample.render 28 | |> fun x -> System.IO.File.WriteAllText(tfn, x) 29 | |> ignore 30 | 31 | let p = new System.Diagnostics.Process() 32 | p.StartInfo.FileName <- tfn 33 | p.StartInfo.UseShellExecute <- true 34 | p.Start() |> ignore 35 | 36 | 0 37 | -------------------------------------------------------------------------------- /tests/Giraffe.ViewEngine.Tests/Giraffe.ViewEngine.Tests.fsproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net6.0 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | PreserveNewest 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/Giraffe.ViewEngine/StringBuilderPool.fs: -------------------------------------------------------------------------------- 1 | namespace Giraffe.ViewEngine 2 | 3 | open System 4 | open System.Text 5 | 6 | module internal PoolLimits = 7 | let internal MinimumCapacity = 5000 8 | let internal MaximumCapacity = 40000 9 | let internal MaximumLifetime = TimeSpan.FromMinutes 10.0 10 | 11 | type public StringBuilderPool = 12 | [] 13 | static val mutable private isEnabled : bool 14 | 15 | [] 16 | static val mutable private instance : StringBuilder 17 | 18 | [] 19 | static val mutable private created : DateTimeOffset 20 | 21 | static member public IsEnabled 22 | with get () = StringBuilderPool.isEnabled 23 | and set flag = StringBuilderPool.isEnabled <- flag 24 | 25 | static member internal Rent () = 26 | match StringBuilderPool.IsEnabled with 27 | | false -> new StringBuilder(PoolLimits.MinimumCapacity) 28 | | true -> 29 | let lifetime = DateTimeOffset.Now - StringBuilderPool.created 30 | let expired = lifetime > PoolLimits.MaximumLifetime 31 | let sb = StringBuilderPool.instance 32 | if not expired && sb <> null then 33 | StringBuilderPool.instance <- null 34 | sb.Clear() 35 | else new StringBuilder(PoolLimits.MinimumCapacity) 36 | 37 | static member internal Release (sb : StringBuilder) = 38 | if sb.Capacity <= PoolLimits.MaximumCapacity then 39 | StringBuilderPool.instance <- sb 40 | StringBuilderPool.created <- DateTimeOffset.Now -------------------------------------------------------------------------------- /tests/Giraffe.ViewEngine.Tests/Tests.fs: -------------------------------------------------------------------------------- 1 | module Giraffe.ViewEngine.Tests 2 | 3 | open System 4 | open Xunit 5 | open Giraffe.ViewEngine 6 | 7 | let removeNewLines (html : string) : string = 8 | html.Replace(Environment.NewLine, String.Empty) 9 | 10 | [] 11 | let ``Single html root should compile`` () = 12 | let doc = html [] [] 13 | let html = 14 | doc 15 | |> RenderView.AsString.htmlDocument 16 | |> removeNewLines 17 | Assert.Equal("", html) 18 | 19 | [] 20 | let ``Anchor should contain href, target and content`` () = 21 | let anchor = 22 | a [ attr "href" "http://example.org"; attr "target" "_blank" ] [ str "Example" ] 23 | let html = RenderView.AsString.xmlNode anchor 24 | Assert.Equal("Example", html) 25 | 26 | [] 27 | let ``Script should contain src, lang and async`` () = 28 | let scriptFile = 29 | script [ attr "src" "http://example.org/example.js"; attr "lang" "javascript"; flag "async" ] [] 30 | let html = RenderView.AsString.xmlNode scriptFile 31 | Assert.Equal("", html) 32 | 33 | [] 34 | let ``Nested content should render correctly`` () = 35 | let nested = 36 | div [] [ 37 | comment "this is a test" 38 | h1 [] [ str "Header" ] 39 | p [] [ 40 | rawText "Lorem " 41 | strong [] [ str "Ipsum" ] 42 | str " dollar" 43 | ] ] 44 | let html = 45 | nested 46 | |> RenderView.AsString.xmlNode 47 | |> removeNewLines 48 | Assert.Equal("

Header

Lorem Ipsum dollar

", html) 49 | 50 | [] 51 | let ``Void tag in XML should be self closing tag`` () = 52 | let unary = br [] |> RenderView.AsString.xmlNode 53 | Assert.Equal("
", unary) 54 | 55 | [] 56 | let ``Void tag in HTML should be unary tag`` () = 57 | let unary = br [] |> RenderView.AsString.htmlNode 58 | Assert.Equal("
", unary) 59 | -------------------------------------------------------------------------------- /RELEASE_NOTES.md: -------------------------------------------------------------------------------- 1 | Release Notes 2 | ============= 3 | 4 | ## 2.0.0-alpha-1 5 | 6 | - Updated to .NET 6 and Giraffe 6.0.0-alpha-* 7 | - Improved performance by removing redundant `ToArray` functions and making `XmlElement` a struct 8 | 9 | ## 1.4.0 10 | 11 | - Added `slot` and `template` elements 12 | - Added .NET Standard 2.0 support for full framework support 13 | 14 | ## 1.3.0 15 | 16 | Upgraded to `net5.0` target framework. 17 | 18 | `Giraffe.ViewEngine` version `1.2.0` and version `1.3.0` are identical in functionality. The only difference is that `1.2.0` targets `netcoreapp3.1` and `1.3.0` targets `net5.0`. If you cannot upgrade your .NET Core project to `net5.0` yet then stay on version `1.2.0`. 19 | 20 | New features and bug fixes will continue off the `1.3.0` version and therefore only target `net5.0` going forward. The upgrade path from `netcoreapp3.1` to `net5.0` is so minimal that it is a reasonable expectation and not worth the effort to support both target frameworks. 21 | 22 | ## 1.2.0 23 | 24 | - Added missing `iframe` element ([#9](https://github.com/giraffe-fsharp/Giraffe.ViewEngine/issues/9)) 25 | 26 | ## 1.1.1 27 | 28 | - Fixed the `strf` function (see [#6](https://github.com/giraffe-fsharp/Giraffe.ViewEngine/issues/6)) 29 | 30 | ## 1.1.0 31 | 32 | - Added `strf` which is a shortcut for the commonly used `sprintf fmt |> encodedText` function. 33 | - Added a few missing HTML elements and attributes: 34 | - Elements: `picture` 35 | - Attributes: `_color`, `_property`, `_srcset` 36 | 37 | ## 1.0.0 38 | 39 | Original port from Giraffe with additional improvements/changes: 40 | 41 | - Zero dependency library 42 | - One can create a separate project for Giraffe views in their solution (`.sln`) with zero dependencies. This significantly speeds up compilation time and therefore improves an active development experience via `dotnet watch`. 43 | - Dropped support for all target frameworks except `netcoreapp3.1` in preparation for the upcoming .NET 5 release 44 | - Renamed the namespace from `GiraffeViewEngine` to `Giraffe.ViewEngine` 45 | - Made the `ViewBuilder` module private and exposed public render functions via three new modules: 46 | - `RenderView.IntoStringBuilder` replaces the old `ViewBuilder` functions 47 | - `RenderView.AsString` replaces all old `render...` functions 48 | - `RenderView.AsBytes` new module to efficiently output views as byte arrays -------------------------------------------------------------------------------- /src/Giraffe.ViewEngine/Giraffe.ViewEngine.fsproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Giraffe.ViewEngine 5 | An F# view engine for Giraffe and other ASP.NET Core web applications. 6 | Copyright 2020 Dustin Moris Gorski 7 | Dustin Moris Gorski and contributors 8 | en-GB 9 | 10 | 11 | net6.0;netstandard2.0 12 | portable 13 | Library 14 | true 15 | false 16 | true 17 | true 18 | 19 | 20 | Giraffe.ViewEngine 21 | Giraffe;View;Engine;ASP.NET Core;FSharp;Functional;Http;Web;Framework;Micro;Service 22 | https://raw.githubusercontent.com/giraffe-fsharp/Giraffe.ViewEngine/master/RELEASE_NOTES.md 23 | https://github.com/giraffe-fsharp/Giraffe.ViewEngine 24 | giraffe-64x64.png 25 | Apache-2.0 26 | true 27 | git 28 | https://github.com/giraffe-fsharp/Giraffe.ViewEngine 29 | 30 | 31 | true 32 | true 33 | 34 | $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb 35 | FS2003;FS0044 36 | 37 | 38 | 39 | 40 | true 41 | $(PackageIconUrl) 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: .NET Core 2 | on: 3 | push: 4 | pull_request: 5 | release: 6 | types: 7 | - published 8 | env: 9 | # Stop wasting time caching packages 10 | DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true 11 | # Disable sending usage data to Microsoft 12 | DOTNET_CLI_TELEMETRY_OPTOUT: true 13 | # Project name to pack and publish 14 | PROJECT_NAME: Giraffe.ViewEngine 15 | # GitHub Packages Feed settings 16 | GITHUB_FEED: https://nuget.pkg.github.com/giraffe-fsharp/ 17 | GITHUB_USER: dustinmoris 18 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 19 | # Official NuGet Feed settings 20 | NUGET_FEED: https://api.nuget.org/v3/index.json 21 | NUGET_KEY: ${{ secrets.NUGET_KEY }} 22 | jobs: 23 | build: 24 | runs-on: ${{ matrix.os }} 25 | strategy: 26 | matrix: 27 | os: [ ubuntu-latest, windows-latest, macos-latest ] 28 | steps: 29 | - name: Checkout 30 | uses: actions/checkout@v2 31 | - name: Setup .NET Core 32 | uses: actions/setup-dotnet@v1 33 | with: 34 | dotnet-version: 6.0.100 35 | - name: Restore 36 | run: dotnet restore 37 | - name: Build 38 | run: dotnet build -c Release --no-restore 39 | - name: Test 40 | run: dotnet test -c Release 41 | - name: Pack 42 | if: matrix.os == 'ubuntu-latest' 43 | run: dotnet pack -v normal -c Release --no-restore --include-symbols --include-source -p:PackageVersion=$GITHUB_RUN_ID src/$PROJECT_NAME/$PROJECT_NAME.*proj 44 | - name: Upload Artifact 45 | if: matrix.os == 'ubuntu-latest' 46 | uses: actions/upload-artifact@v2 47 | with: 48 | name: nupkg 49 | path: ./src/${{ env.PROJECT_NAME }}/bin/Release/*.nupkg 50 | prerelease: 51 | needs: build 52 | if: github.ref == 'refs/heads/develop' 53 | runs-on: ubuntu-latest 54 | steps: 55 | - name: Download Artifact 56 | uses: actions/download-artifact@v4.1.7 57 | with: 58 | name: nupkg 59 | - name: Push to GitHub Feed 60 | run: | 61 | for f in ./nupkg/*.nupkg 62 | do 63 | curl -vX PUT -u "$GITHUB_USER:$GITHUB_TOKEN" -F package=@$f $GITHUB_FEED 64 | done 65 | deploy: 66 | needs: build 67 | if: github.event_name == 'release' 68 | runs-on: ubuntu-latest 69 | steps: 70 | - uses: actions/checkout@v2 71 | - name: Setup .NET Core 72 | uses: actions/setup-dotnet@v1 73 | with: 74 | dotnet-version: 6.0.100 75 | - name: Create Release NuGet package 76 | run: | 77 | arrTag=(${GITHUB_REF//\// }) 78 | VERSION="${arrTag[2]}" 79 | echo Version: $VERSION 80 | VERSION="${VERSION//v}" 81 | echo Clean Version: $VERSION 82 | dotnet pack -v normal -c Release --include-symbols --include-source -p:PackageVersion=$VERSION -o nupkg src/$PROJECT_NAME/$PROJECT_NAME.*proj 83 | - name: Push to GitHub Feed 84 | run: | 85 | for f in ./nupkg/*.nupkg 86 | do 87 | curl -vX PUT -u "$GITHUB_USER:$GITHUB_TOKEN" -F package=@$f $GITHUB_FEED 88 | done 89 | - name: Push to NuGet Feed 90 | run: dotnet nuget push ./nupkg/*.nupkg --source $NUGET_FEED --skip-duplicate --api-key $NUGET_KEY -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at giraffe@dusted.codes. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /Giraffe.ViewEngine.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29613.14 5 | MinimumVisualStudioVersion = 15.0.26124.0 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{2220E7F8-8762-4E3E-BA32-30BCD8915F04}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{46B33AE0-AFED-4B25-A515-CFE125BE9CF4}" 9 | EndProject 10 | Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "Giraffe.ViewEngine", "src\Giraffe.ViewEngine\Giraffe.ViewEngine.fsproj", "{18666EED-40CE-4494-9103-B2C4557EAEF2}" 11 | EndProject 12 | Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "Giraffe.ViewEngine.Benchmarks", "tests\Giraffe.ViewEngine.Benchmarks\Giraffe.ViewEngine.Benchmarks.fsproj", "{B73D9521-FF59-4514-B26B-E17CEDDDD7B6}" 13 | EndProject 14 | Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "Giraffe.ViewEngine.Tests", "tests\Giraffe.ViewEngine.Tests\Giraffe.ViewEngine.Tests.fsproj", "{5EBF86C7-6FF5-45D6-9787-A77FCF77188D}" 15 | EndProject 16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_root", "_root", "{55329640-BF2E-411E-8F97-A397DA138E7F}" 17 | ProjectSection(SolutionItems) = preProject 18 | LICENSE = LICENSE 19 | README.md = README.md 20 | RELEASE_NOTES.md = RELEASE_NOTES.md 21 | NuGet.config = NuGet.config 22 | .gitattributes = .gitattributes 23 | .gitignore = .gitignore 24 | CODE_OF_CONDUCT.md = CODE_OF_CONDUCT.md 25 | EndProjectSection 26 | EndProject 27 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{AE9081DB-1992-4AEC-9D84-F276047E82D6}" 28 | EndProject 29 | Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Giraffe.ViewEngine.Sample", "samples\Giraffe.ViewEngine.Sample\Giraffe.ViewEngine.Sample.fsproj", "{AD23CC18-C2ED-47CB-847F-34CB5460259B}" 30 | EndProject 31 | Global 32 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 33 | Debug|Any CPU = Debug|Any CPU 34 | Release|Any CPU = Release|Any CPU 35 | EndGlobalSection 36 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 37 | {18666EED-40CE-4494-9103-B2C4557EAEF2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {18666EED-40CE-4494-9103-B2C4557EAEF2}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {18666EED-40CE-4494-9103-B2C4557EAEF2}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {18666EED-40CE-4494-9103-B2C4557EAEF2}.Release|Any CPU.Build.0 = Release|Any CPU 41 | {B73D9521-FF59-4514-B26B-E17CEDDDD7B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 42 | {B73D9521-FF59-4514-B26B-E17CEDDDD7B6}.Debug|Any CPU.Build.0 = Debug|Any CPU 43 | {B73D9521-FF59-4514-B26B-E17CEDDDD7B6}.Release|Any CPU.ActiveCfg = Release|Any CPU 44 | {B73D9521-FF59-4514-B26B-E17CEDDDD7B6}.Release|Any CPU.Build.0 = Release|Any CPU 45 | {5EBF86C7-6FF5-45D6-9787-A77FCF77188D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 46 | {5EBF86C7-6FF5-45D6-9787-A77FCF77188D}.Debug|Any CPU.Build.0 = Debug|Any CPU 47 | {5EBF86C7-6FF5-45D6-9787-A77FCF77188D}.Release|Any CPU.ActiveCfg = Release|Any CPU 48 | {5EBF86C7-6FF5-45D6-9787-A77FCF77188D}.Release|Any CPU.Build.0 = Release|Any CPU 49 | {AD23CC18-C2ED-47CB-847F-34CB5460259B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 50 | {AD23CC18-C2ED-47CB-847F-34CB5460259B}.Debug|Any CPU.Build.0 = Debug|Any CPU 51 | {AD23CC18-C2ED-47CB-847F-34CB5460259B}.Release|Any CPU.ActiveCfg = Release|Any CPU 52 | {AD23CC18-C2ED-47CB-847F-34CB5460259B}.Release|Any CPU.Build.0 = Release|Any CPU 53 | EndGlobalSection 54 | GlobalSection(SolutionProperties) = preSolution 55 | HideSolutionNode = FALSE 56 | EndGlobalSection 57 | GlobalSection(NestedProjects) = preSolution 58 | {18666EED-40CE-4494-9103-B2C4557EAEF2} = {2220E7F8-8762-4E3E-BA32-30BCD8915F04} 59 | {B73D9521-FF59-4514-B26B-E17CEDDDD7B6} = {46B33AE0-AFED-4B25-A515-CFE125BE9CF4} 60 | {5EBF86C7-6FF5-45D6-9787-A77FCF77188D} = {46B33AE0-AFED-4B25-A515-CFE125BE9CF4} 61 | {AD23CC18-C2ED-47CB-847F-34CB5460259B} = {AE9081DB-1992-4AEC-9D84-F276047E82D6} 62 | EndGlobalSection 63 | GlobalSection(ExtensibilityGlobals) = postSolution 64 | SolutionGuid = {B37FB108-DCCC-4EDD-AEED-8F3D069356D6} 65 | EndGlobalSection 66 | EndGlobal 67 | -------------------------------------------------------------------------------- /tests/Giraffe.ViewEngine.Benchmarks/Program.fs: -------------------------------------------------------------------------------- 1 | module Giraffe.ViewEngine.Benchmarks 2 | 3 | open BenchmarkDotNet.Attributes; 4 | open BenchmarkDotNet.Running; 5 | open Giraffe.ViewEngine 6 | open System.Text 7 | open System.Buffers 8 | 9 | [] 10 | type HtmlUtf8Benchmark() = 11 | 12 | let doc = 13 | div [] [ 14 | div [ _class "top-bar" ] 15 | [ div [ _class "top-bar-left" ] 16 | [ ul [ _class "dropdown menu" 17 | _data "dropdown-menu" "" ] 18 | [ li [ _class "menu-text" ] 19 | [ rawText "Site Title" ] 20 | li [ ] 21 | [ a [ _href "#" ] 22 | [ str """One """ ] 23 | ul [ _class "menu vertical" ] 24 | [ li [ ] 25 | [ a [ _href "#" ] 26 | [ rawText "One" ] ] 27 | li [ ] 28 | [ a [ _href "#" ] 29 | [ str "Two" ] ] 30 | li [ ] 31 | [ a [ _href "#" ] 32 | [ rawText "Three" ] ] ] ] 33 | li [ ] 34 | [ a [ _href "#" ] 35 | [ str "Two" ] ] 36 | li [ ] 37 | [ a [ _href "#" ] 38 | [ str "Three" ] ] ] ] 39 | div [ _class "top-bar-right" ] 40 | [ ul [ _class "menu" ] 41 | [ li [ ] 42 | [ input [ _type "search" 43 | _placeholder "Search" ] ] 44 | li [ ] 45 | [ button [ _type "button" 46 | _class "button" ] 47 | [ rawText "Search" ] ] ] ] ] 48 | ] 49 | 50 | let stringBuilder = StringBuilder(16 * 1024) 51 | 52 | [] 53 | member this.Default() = 54 | RenderView.AsBytes.htmlDocument doc 55 | 56 | [] 57 | member this.CachedStringBuilder() = 58 | RenderView.IntoStringBuilder.htmlDocument stringBuilder doc 59 | stringBuilder.ToString() |> Encoding.UTF8.GetBytes |> ignore 60 | stringBuilder.Clear(); 61 | 62 | [] 63 | member this.CachedStringBuilderPooledUtf8Array() = 64 | RenderView.IntoStringBuilder.htmlDocument stringBuilder doc 65 | let chars = ArrayPool.Shared.Rent(stringBuilder.Length) 66 | stringBuilder.CopyTo(0, chars, 0, stringBuilder.Length) 67 | Encoding.UTF8.GetBytes(chars, 0, stringBuilder.Length) |> ignore 68 | ArrayPool.Shared.Return(chars) 69 | stringBuilder.Clear() 70 | 71 | [] 72 | type HtmlBuildBenchmark() = 73 | 74 | let doc() = 75 | div [] [ 76 | div [ _class "top-bar" ] 77 | [ div [ _class "top-bar-left" ] 78 | [ ul [ _class "dropdown menu" 79 | _data "dropdown-menu" "" ] 80 | [ li [ _class "menu-text" ] 81 | [ rawText "Site Title" ] 82 | li [ ] 83 | [ a [ _href "#" ] 84 | [ str """One """ ] 85 | ul [ _class "menu vertical" ] 86 | [ li [ ] 87 | [ a [ _href "#" ] 88 | [ rawText "One" ] ] 89 | li [ ] 90 | [ a [ _href "#" ] 91 | [ str "Two" ] ] 92 | li [ ] 93 | [ a [ _href "#" ] 94 | [ rawText "Three" ] ] ] ] 95 | li [ ] 96 | [ a [ _href "#" ] 97 | [ str "Two" ] ] 98 | li [ ] 99 | [ a [ _href "#" ] 100 | [ str "Three" ] ] ] ] 101 | div [ _class "top-bar-right" ] 102 | [ ul [ _class "menu" ] 103 | [ li [ ] 104 | [ input [ _type "search" 105 | _placeholder "Search" ] ] 106 | li [ ] 107 | [ button [ _type "button" 108 | _class "button" ] 109 | [ rawText "Search" ] ] ] ] ] 110 | ] 111 | 112 | [] 113 | member this.Default() = 114 | doc() 115 | 116 | [] 117 | let main args = 118 | let asm = typeof.Assembly 119 | BenchmarkSwitcher.FromAssembly(asm).Run(args) |> ignore 120 | 0 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | 332 | # macOS 333 | .DS_Store 334 | 335 | # Ionide 336 | .ionide/ 337 | 338 | # Visual Studio Code 339 | .vscode -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Giraffe](https://raw.githubusercontent.com/giraffe-fsharp/Giraffe/master/giraffe.png) 2 | 3 | # Giraffe.ViewEngine 4 | 5 | An F# view engine for [Giraffe](https://github.com/giraffe-fsharp/Giraffe) and other ASP.NET Core web applications. 6 | 7 | [![NuGet Info](https://buildstats.info/nuget/Giraffe.ViewEngine?includePreReleases=true)](https://www.nuget.org/packages/Giraffe.ViewEngine/) 8 | 9 | ### Linux, macOS and Windows Build Status 10 | 11 | ![.NET Core](https://github.com/giraffe-fsharp/Giraffe.ViewEngine/workflows/.NET%20Core/badge.svg?branch=develop) 12 | 13 | [![Build history](https://buildstats.info/github/chart/giraffe-fsharp/Giraffe.ViewEngine?branch=develop&includeBuildsFromPullRequest=false)](https://github.com/giraffe-fsharp/Giraffe.ViewEngine/actions?query=branch%3Adevelop++) 14 | 15 | ## Table of contents 16 | 17 | - [About](#about) 18 | - [Documentation](#documentation) 19 | - [Overview](#overview) 20 | - [HTML Elements and Attributes](#html-elements-and-attributes) 21 | - [Text Content](#text-content) 22 | - [Naming Convention](#naming-convention) 23 | - [Javascript event handlers](#javascript-event-handlers) 24 | - [Custom Elements and Attributes](#custom-elements-and-attributes) 25 | - [Rendering Views](#rendering-views) 26 | - [Rendering HTML](#rendering-html) 27 | - [Rendering XML](#rendering-xml) 28 | - [StringBuilder Pools](#stringbuilder-pools) 29 | - [Common Patterns](#common-patterns) 30 | - [Master Pages](#master-pages) 31 | - [Partial Views](#partial-views) 32 | - [Model Binding](#model-binding) 33 | - [Logical Constructs](#logical-constructs) 34 | - [Best Practices](#best-practices) 35 | - [Samples](#samples) 36 | - [Attribution to original authors](#attribution-to-original-authors) 37 | - [Nightly builds and NuGet feed](#nightly-builds-and-nuget-feed) 38 | - [License](#license) 39 | 40 | ## About 41 | 42 | The `Giraffe.ViewEngine` is a UI framework which uses traditional F# functions and types to build rich HTML or XML based web views. This means that views built with the `Giraffe.ViewEngine` are automatically compiled into an assembly, don't require any disk I/O to load or render views and users of the `Giraffe.ViewEngine` can utilise the full power of F# to create custom views in every way possible. 43 | 44 | Originally the `Giraffe.ViewEngine` was part of the [Giraffe web framework](https://github.com/giraffe-fsharp/giraffe) but has been completely separated since then and can be used on its own with any other .NET Core web application today. 45 | 46 | ## Documentation 47 | 48 | ### Overview 49 | 50 | The `Giraffe.ViewEngine` is an extremely light weight F# DSL (Domain Specific Language) for building HTML. 51 | 52 | It is centered around the following types: 53 | 54 | ```fsharp 55 | type XmlAttribute = 56 | | KeyValue of string * string 57 | | Boolean of string 58 | 59 | type XmlElement = string * XmlAttribute[] // Name * XML attributes 60 | 61 | type XmlNode = 62 | | ParentNode of XmlElement * XmlNode list // An XML element which contains nested XML elements 63 | | VoidElement of XmlElement // An XML element which cannot contain nested XML (e.g.
or
) 64 | | Text of string // Text content 65 | ``` 66 | 67 | The DSL mainly consists of F# functions which will create objects of one of the above defined types. Currently the `Giraffe.ViewEngine` has functions for all of the standard html tags, such as `head`, `body`, `h1`, etc. 68 | 69 | Please see [HTML Elements and Attributes](#html-elements-and-attributes) for further details and to get a better understanding. 70 | 71 | ### HTML Elements and Attributes 72 | 73 | HTML elements and attributes are defined as F# objects: 74 | 75 | ```fsharp 76 | let indexView = 77 | html [] [ 78 | head [] [ 79 | title [] [ str "Giraffe Sample" ] 80 | ] 81 | body [] [ 82 | h1 [] [ str "I |> F#" ] 83 | p [ _class "some-css-class"; _id "someId" ] [ 84 | str "Hello World" 85 | ] 86 | ] 87 | ] 88 | ``` 89 | 90 | A HTML element can either be a `ParentNode`, a `VoidElement` or a `Text` element. 91 | 92 | For example the `` or `
` tags are typical `ParentNode` elements. They can hold an `XmlAttribute list` and a second `XmlElement list` for their child elements: 93 | 94 | ```fsharp 95 | let someHtml = div [] [] 96 | ``` 97 | 98 | All `ParentNode` elements accept these two parameters: 99 | 100 | ```fsharp 101 | let someHtml = 102 | div [ _id "someId"; _class "css-class" ] [ 103 | a [ _href "https://example.org" ] [ str "Some text..." ] 104 | ] 105 | ``` 106 | 107 | Most HTML tags are `ParentNode` elements, however there is a few HTML tags which cannot hold any child elements, such as `
`, `
` or `` tags. These are represented as `VoidElement` objects and only accept the `XmlAttribute list` as single parameter: 108 | 109 | ```fsharp 110 | let someHtml = 111 | div [] [ 112 | br [] 113 | hr [ _class "css-class-for-hr" ] 114 | p [] [ str "bla blah" ] 115 | ] 116 | ``` 117 | 118 | Attributes are further classified into two different cases. First and most commonly there are `KeyValue` attributes: 119 | 120 | ```fsharp 121 | a [ 122 | _href "http://url.com" 123 | _target "_blank" 124 | _class "class1" ] [ str "Click here" ] 125 | ``` 126 | 127 | As the name suggests, they have a key, such as `class` and a value such as the name of a CSS class. 128 | 129 | The second category of attributes are `Boolean` flags. There are not many but some HTML attributes which do not require any value (e.g. `async` or `defer` in script tags). The presence of such an attribute means that the feature is turned on, otherwise it is turned off: 130 | 131 | ```fsharp 132 | script [ _src "some.js"; _async ] [] 133 | ``` 134 | 135 | There's also a wealth of [accessibility attributes](https://www.w3.org/TR/html-aria/) available under the `Giraffe.ViewEngine.Accessibility` module (needs to be explicitly opened). 136 | 137 | ### Text Content 138 | 139 | Naturally the most frequent content in any HTML document is pure text: 140 | 141 | ```html 142 |
143 |

This is text content

144 |

This is even more text content!

145 |
146 | ``` 147 | 148 | The `Giraffe.ViewEngine` lets one create pure text content as a `Text` element. A `Text` element can either be generated via the `rawText` or `encodedText` (or the short alias `str`) functions: 149 | 150 | ```fsharp 151 | let someHtml = 152 | div [] [ 153 | p [] [ rawText "
Hello World
" ] 154 | p [] [ encodedText "
Hello World
" ] 155 | ] 156 | ``` 157 | 158 | The `rawText` function will create an object of type `XmlNode` where the content will be rendered in its original form and the `encodedText`/`str` function will output a string where the content has been HTML encoded. 159 | 160 | In this example the first `p` element will literally output the string as it is (`
Hello World
`) while the second `p` element will output the value as HTML encoded string `<div>Hello World</div>`. 161 | 162 | Please be aware that the the usage of `rawText` is mainly designed for edge cases where someone would purposefully want to inject HTML (or JavaScript) code into a rendered view. If not used carefully this could potentially lead to serious security vulnerabilities and therefore should be used only when explicitly required. 163 | 164 | Most cases and particularly any user provided content should always be output via the `encodedText`/`str` function. 165 | 166 | ### Naming Convention 167 | 168 | The `Giraffe.ViewEngine` has a naming convention which lets you easily determine the correct function name without having to know anything about the view engine's implementation. 169 | 170 | All HTML tags are defined as `XmlNode` elements under the exact same name as they are named in HTML. For example the `` tag would be `html [] []`, an `` tag would be `a [] []` and a `` or `` would be the `span [] []` or `canvas [] []` function. 171 | 172 | HTML attributes follow the same naming convention except that attributes have an underscore prepended. For example the `class` attribute would be `_class` and the `src` attribute would be `_src` in the `Giraffe.ViewEngine`. 173 | 174 | The underscore does not only help to distinguish an attribute from an element, but also avoid a naming conflict between tags and attributes of the same name (e.g. `
` vs. ``). 175 | 176 | If a HTML attribute has a hyphen in the name (e.g. `accept-charset`) then the equivalent Giraffe attribute would be written in camel case notion after the initial underscore (e.g. `_acceptCharset`). 177 | 178 | *Should you find a HTML tag or attribute missing in the `Giraffe.ViewEngine` then you can either [create it yourself](#custom-elements-and-attributes) or send a [pull request on GitHub](https://github.com/giraffe-fsharp/Giraffe.ViewEngine/pulls).* 179 | 180 | ### Javascript event handlers 181 | 182 | It is possible to add JavaScript event handlers to HTML elements using the `Giraffe.ViewEngine`. These event handlers (all prefixed with names starting with `_on`, for example `_onclick`, `_onmouseover`) can either execute inline JavaScript code or can invoke functions that are part of the `window` scope. 183 | 184 | This example illustrates how inline JavaScript could be used to log to the console when a button is clicked: 185 | 186 | ```fsharp 187 | let inlineJSButton = 188 | button [_id "inline-js" 189 | _onclick "console.log(\"Hello from the 'inline-js' button!\");"] [str "Say Hello" ] 190 | ``` 191 | 192 | There are some caveats with this approach, namely that 193 | * ...it is not very scalable to write JavaScript inline in this manner, and more pressing... 194 | * ...the `Giraffe.ViewEngine` HTML-encodes the text provided to the `_onX` attributes. 195 | 196 | To get around this, you can write dedicated scripts in your HTML and reference the functions from your event handlers: 197 | 198 | ```fsharp 199 | let page = 200 | div [] [ 201 | script [_type "application/javascript"] [ 202 | rawText """ 203 | window.greet = function () { 204 | console.log("ping from the greet method"); 205 | } 206 | """ 207 | ] 208 | button [_id "script-tag-js" 209 | _onclick "greet();"] [str "Say Hello"] 210 | ] 211 | ``` 212 | 213 | Here it's important to note that we've included the text of our script using the `rawText` tag. This ensures that our text is not encoded by the `Giraffe.ViewEngine` so that it remains as it was written. 214 | 215 | However, writing large quantities of JavaScript in this manner can be difficult, because you don't have access to the large ecosystem of javascript editor tooling. In this case you should write your functions in another script and use a `script` tag element to reference your script, then add the desired function to your HTML element's event handler. 216 | 217 | Say you had a JavaScript file named `greet.js` and had configured Giraffe to serve that script from the WebRoot. Let us also say that the content of that script was: 218 | 219 | ```javascript 220 | function greet() { 221 | console.log("Hello from the greet function of greet.js!"); 222 | } 223 | ``` 224 | 225 | Then, you could reference that javascript via a script element, and use `greet` in your event handler like so: 226 | 227 | ```fsharp 228 | let page = 229 | html [] [ 230 | head [] [ 231 | script [_type "application/javascript" 232 | _src "/greet.js"] [] // include our `greet.js` function dynamically 233 | ] 234 | body [] [ 235 | button [_id "greet-btn" 236 | _onclick "greet()"] [] // use the `greet()` function from `greet.js` to say hello 237 | ] 238 | ] 239 | ``` 240 | 241 | In this way, you can write `greet.js` with all of your expected tooling, and still hook up the event handlers all in one place in the `Giraffe.ViewEngine`. 242 | 243 | ### Custom Elements and Attributes 244 | 245 | Adding new elements or attributes is normally as simple as a single line of code: 246 | 247 | ```fsharp 248 | open Giraffe.ViewEngine 249 | 250 | // If there was a new HTML element: 251 | let foo = tag "foo" 252 | 253 | // If is an element which cannot hold any content then create it as voidTag: 254 | let foo = voidTag "foo" 255 | 256 | // If has a new attribute called bar then create a new bar attribute: 257 | let _bar = attr "bar" 258 | 259 | // if the bar attribute is a boolean flag: 260 | let _bar = flag "bar" 261 | ``` 262 | 263 | Alternatively you can also create new elements and attributes from inside another element: 264 | 265 | ```fsharp 266 | let someHtml = 267 | div [] [ 268 | tag "foo" [ attr "bar" "blah" ] [ 269 | voidTag "otherFoo" [ flag "flag1" ] 270 | ] 271 | ] 272 | ``` 273 | 274 | ### Rendering Views 275 | 276 | Rendering views with the `Giraffe.ViewEngine` can be done in several ways. The `RenderView` module exposes three sub modules which can be used to specify the desired output format: 277 | 278 | - `RenderView.IntoStringBuilder` implements functions to render a view into a `StringBuilder` object which can be used for further processing. 279 | - `RenderView.AsString` implements functions to output a view directly as a `string`. 280 | - `RenderView.AsBytes` implements functions to output a view directly as a `byte array`. 281 | 282 | All three sub modules implement the following public functions: 283 | 284 | - `htmlDocument` 285 | - `htmlNodes` 286 | - `htmlNode` 287 | - `xmlNodes` 288 | - `xmlNode` 289 | 290 | #### Rendering HTML 291 | 292 | The `htmlDocument` function takes a single `XmlNode` as input parameter and renders a HTML page with a `DOCTYPE` declaration. This function should be used for rendering a complete HTML document. 293 | 294 | The `htmlNodes` function takes an `XmlNode list` as input parameter and will output a single HTML string containing all the rendered HTML code. The `htmlNode` function renders a single `XmlNode` element into a valid HTML string. Both, the `htmlNodes` and `htmlNode` function are useful for use cases where a HTML snippet needs to be created without a `DOCTYPE` declaration (e.g. email templates, etc.). 295 | 296 | #### Rendering XML 297 | 298 | Views cannot only be rendered into HTML pages but also into other XML based content such as SVG images or other data objects. 299 | 300 | The `xmlNodes` and `xmlNode` function are identical to `htmlNodes` and `htmlNode`, except that they will render void elements differently: 301 | 302 | ```fsharp 303 | let someTag = voidTag "foo" 304 | let someContent = someTag [] 305 | 306 | // Void tag will be rendered to valid HTML: 307 | let output1 = RenderView.AsString.htmlNode someContent 308 | 309 | // Void tag will be rendered to valid XML: 310 | let output2 = RenderView.AsString.xmlNode someContent 311 | ``` 312 | 313 | #### StringBuilder Pools 314 | 315 | All functions from the `RenderView.AsString` and `RenderView.AsBytes` modules are using a thread static `StringBuilderPool` to avoid the creation of large `StringBuilder` objects for each render call and dynamically grow/shrink that pool based on the application's needs. However if the application is running into any memory issues then this performance feature can be disabled by setting `StringBuilderPool.IsEnabled` to false: 316 | 317 | ```fsharp 318 | StringBuilderPool.IsEnabled <- false 319 | ``` 320 | 321 | Additionally the `RenderView.IntoStringBuilder` module can be used if full control of the `StringBuilder` object is required: 322 | 323 | ```fsharp 324 | open System.Text 325 | open Giraffe.ViewEngine 326 | 327 | let someHtml = 328 | div [] [ 329 | tag "foo" [ attr "bar" "blah" ] [ 330 | voidTag "otherFoo" [ flag "flag1" ] 331 | ] 332 | ] 333 | 334 | // Create your own StringBuilder, which gives the caller 335 | // full control of the lifecycle of the object: 336 | let sb = new StringBuilder() 337 | 338 | // Perform actions on the `sb` object... 339 | sb.AppendLine "This is a HTML snippet inside a markdown string:" 340 | .AppendLine "" 341 | .AppendLine "```html" |> ignore 342 | 343 | // Using RederView.IntoStringBuilder some HTML content can be written 344 | // directly into the given StringBuilder object: 345 | let sb' = RederView.IntoStringBuilder.htmlNode sb someHtml 346 | 347 | // Perform more actions on the `sb` object... 348 | sb'.AppendLine "```" |> ignore 349 | 350 | let markdownOutput = sb'.ToString() 351 | ``` 352 | 353 | ### Common Patterns 354 | 355 | The `Giraffe.ViewEngine` is nothing more but simple F# code dressed up as a DSL which can be used to compose rich HTML content in a structured way. As such it doesn't require any built-in functions to enable common view engine features such as master pages, partial views or model binding. These things can all be accomplished through normal F# coding patterns: 356 | 357 | #### Master Pages 358 | 359 | Creating a master page is as simple as piping two functions together: 360 | 361 | ```fsharp 362 | module Views = 363 | open Giraffe.ViewEngine 364 | 365 | let master (pageTitle : string) (content: XmlNode list) = 366 | html [] [ 367 | head [] [ 368 | title [] [ str pageTitle ] 369 | ] 370 | body [] content 371 | ] 372 | 373 | let index = 374 | let pageTitle = "Giraffe Sample" 375 | [ 376 | h1 [] [ str pageTitle ] 377 | p [] [ str "Hello world!" ] 378 | ] |> master pageTitle 379 | ``` 380 | 381 | ... or even have multiple nested master pages: 382 | 383 | ```fsharp 384 | module Views = 385 | open Giraffe.ViewEngine 386 | 387 | let master1 (pageTitle : string) (content: XmlNode list) = 388 | html [] [ 389 | head [] [ 390 | title [] [ str pageTitle ] 391 | ] 392 | body [] content 393 | ] 394 | 395 | let master2 (content: XmlNode list) = 396 | [ 397 | main [] content 398 | footer [] [ 399 | p [] [ 400 | str "Copyright ..." 401 | ] 402 | ] 403 | ] 404 | 405 | let index = 406 | let pageTitle = "Giraffe Sample" 407 | [ 408 | h1 [] [ str pageTitle ] 409 | p [] [ str "Hello world!" ] 410 | ] |> master2 |> master1 pageTitle 411 | ``` 412 | 413 | #### Partial Views 414 | 415 | Partial views can be codified by calling one function from within another: 416 | 417 | ```fsharp 418 | module Views = 419 | open Giraffe.ViewEngine 420 | 421 | let partial = 422 | footer [] [ 423 | p [] [ 424 | str "Copyright..." 425 | ] 426 | ] 427 | 428 | let master (pageTitle : string) (content: XmlNode list) = 429 | html [] [ 430 | head [] [ 431 | title [] [ str pageTitle ] 432 | ] 433 | body [] content 434 | partial 435 | ] 436 | 437 | let index = 438 | let pageTitle = "Giraffe Sample" 439 | [ 440 | h1 [] [ str pageTitle ] 441 | p [] [ str "Hello world!" ] 442 | ] |> master pageTitle 443 | ``` 444 | 445 | #### Model Binding 446 | 447 | A view which accepts a model is basically a function with an additional parameter: 448 | 449 | ```fsharp 450 | module Views = 451 | open Giraffe.ViewEngine 452 | 453 | let partial = 454 | footer [] [ 455 | p [] [ 456 | str "Copyright..." 457 | ] 458 | ] 459 | 460 | let master (pageTitle : string) (content: XmlNode list) = 461 | html [] [ 462 | head [] [ 463 | title [] [ str pageTitle ] 464 | ] 465 | body [] content 466 | partial 467 | ] 468 | 469 | let index (model : IndexViewModel) = 470 | [ 471 | h1 [] [ str model.PageTitle ] 472 | p [] [ str model.WelcomeText ] 473 | ] |> master model.PageTitle 474 | ``` 475 | 476 | #### Logical Constructs 477 | 478 | Things like if statements, loops and other F# language constructs just work as expected: 479 | 480 | ```fsharp 481 | let partial (books : Book list) = 482 | ul [] [ 483 | yield! 484 | books 485 | |> List.map (fun b -> li [] [ str book.Title ]) 486 | ] 487 | ``` 488 | 489 | Overall the `Giraffe.ViewEngine` is extremely flexible and more feature rich than any other view engine given that it is just normal compiled F# code. 490 | 491 | ### Best Practices 492 | 493 | Due to the huge amount of available HTML tags and their fairly generic (and short) names (e.g. ``, `