emmabastas/elm-mustache/1.1.1

NOTE: the latest version is 1.2.0

Mustache

Parse and render

type alias Ast =
List AstNode

The AST type.

render : String -> Value -> Result (List DeadEnd) String

This is probably the one function you'll want to use. Expects a mustache template string and a JSON object to use as a hash.

import Json.Encode as E


render "Hello, {{world}}!" (E.object [("world", E.string "Pluto")])  --> Ok "Hello, Pluto!"
parse : String -> Result (List DeadEnd) Ast

Parse — but don't render — a template. Useful if you want to use the same template many times with different hashes.

renderParsed : Ast -> Value -> String

Once a template has been parsed with parse it can be rendered with this function.

import Json.Encode as E


ast : Ast
ast = parse "Hello, {{.}}!" |> Result.withDefault []


renderParsed ast (E.string "Pluto")  --> "Hello, Pluto!"


renderParsed ast (E.string "Mercury")  --> "Hello, Mercury!"

Partials

A string can be used as the template in a partial tag

import Json.Encode as E


template : String
template = """
<h2>Names</h2>
{{#names}}
    {{> user}}
{{/names}}
"""


partial : String
partial = "<strong>{{.}}</strong>"


render template
    ( E.object
        [ ("names", E.list E.string [ "Alice", "Bob" ])
        , ("user", E.string partial)
        ]
    )
--> [ ""
--> , "<h2>Names</h2>"
--> , "    <strong>Alice</strong>"
--> , "    <strong>Bob</strong>"
--> , ""
--> , ""
--> ]
--> |> String.join "\n"
--> |> Ok

Niche usecases

htmlEscape : String -> String

Escape the special HTML characters &, ", < and >. This function is used when rendering values in normal variable tags.

type alias Context =
List Value

The context is a list of hashes (both of these terms are specified in the mustache specification) with the head of the list being the innermost hash.

lookup : Context -> Name -> Maybe Value

Given a context, lookup a value in it. The lookup rules follows the ones outlined in the mustache specification.

interpolate : Maybe Value -> String

Interpolate a JSON value into a string. This function is used when inserting a JSON value into a mustache variable.

section : Context -> Name -> (Context -> String) -> String

Render a mustache section. This is only intended to be used by preparsed templates generated with the elm-mustache CLI tool

invertedSection : Context -> Name -> (Context -> String) -> String

Render a mustache inverted section. This is only intended to be used by preparsed templates generated with the elm-mustache CLI tool