Typealiases

The following typealiases are available globally.

  • A pair of tag delimiters, such as ("{{", "}}").

    Seealso

    Configuration.tagDelimiterPair

    Seealso

    Tag.tagDelimiterPair

    Declaration

    Swift

    public typealias TagDelimiterPair = (String, String)
  • Once a WillRenderFunction has entered the context stack, it is called just before tags are about to render, and has the opportunity to replace the value they are about to render.

    let logTags: WillRenderFunction = { (tag: Tag, box: MustacheBox) in
        print("\(tag) will render \(box.value!)")
        return box // don't replace
    }
    
    // By entering the base context of the template, the logTags function
    // will be notified of all tags.
    let template = try! Template(string: "{{# user }}{{ firstName }} {{ lastName }}{{/ user }}")
    template.extendBaseContext(logTags)
    
    // Prints:
    // {{# user }} at line 1 will render { firstName = Errol; lastName = Flynn; }
    // {{ firstName }} at line 1 will render Errol
    // {{ lastName }} at line 1 will render Flynn
    let data = ["user": ["firstName": "Errol", "lastName": "Flynn"]]
    try! template.render(data)
    

    WillRenderFunction don’t have to enter the base context of a template to perform: they can enter the context stack just like any other value, by being attached to a section. In this case, they are only notified of tags inside that section.

    let template = try! Template(string: "{{# user }}{{ firstName }} {{# spy }}{{ lastName }}{{/ spy }}{{/ user }}")
    
    // Prints:
    // {{ lastName }} at line 1 will render Flynn
    let data: [String: Any] = [
        "user": ["firstName": "Errol", "lastName": "Flynn"],
        "spy": logTags
    ]
    try! template.render(data)
    

    Seealso

    DidRenderFunction

    Declaration

    Swift

    public typealias WillRenderFunction = (_ tag: Tag, _ box: MustacheBox) -> Any?
  • RenderFunction is used by the Mustache rendering engine when it renders a variable tag ({{name}} or {{{body}}}) or a section tag ({{#name}}...{{/name}}).

    Output: Rendering

    The return type of RenderFunction is Rendering, a type that wraps a rendered String, and its ContentType (HTML or Text).

    Text renderings are HTML-escaped, except for {{{triple}}} mustache tags, and Text templates (see Configuration.contentType for a full discussion of the content type of templates).

    For example:

    let html: RenderFunction = { (_) in
        return Rendering("<html>", .html)
    }
    let text: RenderFunction = { (_) in
        return Rendering("<text>")   // default content type is text
    }
    
    // Renders "<html>, &lt;text&gt;"
    let template = try! Template(string: "{{html}}, {{text}}")
    let data = ["html": html, "text": text]
    let rendering = try! template.render(data)
    

    Input: RenderingInfo

    The info argument contains a RenderingInfo which provides information about the requested rendering:

    • info.context: Context is the context stack which contains the rendered data.

    • info.tag: Tag is the tag to render.

    • info.tag.type: TagType is the type of the tag (variable or section). You can use this type to have a different rendering for variable and section tags.

    • info.tag.innerTemplateString: String is the inner content of the tag, unrendered. For the section tag {{# person }}Hello {{ name }}!{{/ person }}, it is Hello {{ name }}!.

    • info.tag.render: (Context) throws -> Rendering is a function that renders the inner content of the tag, given a context stack. For example, the section tag {{# person }}Hello {{ name }}!{{/ person }} would render Hello Arthur!, assuming the provided context stack provides Arthur for the key name.

    Example

    As an example, let’s write a RenderFunction which performs the default rendering of a value:

    • {{ value }} and {{{ value }}} renders the built-in Swift String Interpolation of the value: our render function will return a Rendering with content type Text when the rendered tag is a variable tag. The Text content type makes sure that the returned string will be HTML-escaped if needed.

    • {{# value }}...{{/ value }} pushes the value on the top of the context stack, and renders the inner content of section tags.

    The default rendering thus reads:

    let value = ... // Some value
    let renderValue: RenderFunction = { (info: RenderingInfo) throws in
    
        // Default rendering depends on the tag type:
        switch info.tag.type {
    
        case .variable:
            // {{ value }} and {{{ value }}}
    
            // Return the built-in Swift String Interpolation of the value:
            return Rendering("\(value)", .text)
    
        case .section:
            // {{# value }}...{{/ value }}
    
            // Push the value on the top of the context stack:
            let context = info.context.extendedContext(Box(value))
    
            // Renders the inner content of the section tag:
            return try info.tag.render(context)
        }
    }
    
    let template = try! Template(string: "{{value}}")
    let rendering = try! template.render(["value": renderValue])
    

    Declaration

    Swift

    public typealias RenderFunction = (_ info: RenderingInfo) throws -> Rendering

    Parameters

    info

    A RenderingInfo.

    error

    If there is a problem in the rendering, throws an error that describes the problem.

    Return Value

    A Rendering. */

  • Once a DidRenderFunction has entered the context stack, it is called just after tags have been rendered.

    let logRenderings: DidRenderFunction = { (tag: Tag, box: MustacheBox, string: String?) in
        print("\(tag) did render \(box.value!) as `\(string!)`")
    }
    
    // By entering the base context of the template, the logRenderings function
    // will be notified of all tags.
    let template = try! Template(string: "{{# user }}{{ firstName }} {{ lastName }}{{/ user }}")
    template.extendBaseContext(logRenderings)
    
    // Renders "Errol Flynn"
    //
    // Prints:
    // {{ firstName }} at line 1 did render Errol as `Errol`
    // {{ lastName }} at line 1 did render Flynn as `Flynn`
    // {{# user }} at line 1 did render { firstName = Errol; lastName = Flynn; } as `Errol Flynn`
    let data = ["user": ["firstName": "Errol", "lastName": "Flynn"]]
    try! template.render(data)
    

    DidRender functions don’t have to enter the base context of a template to perform: they can enter the context stack just like any other value, by being attached to a section. In this case, they are only notified of tags inside that section.

    let template = try! Template(string: "{{# user }}{{ firstName }} {{# spy }}{{ lastName }}{{/ spy }}{{/ user }}")
    
    // Renders "Errol Flynn"
    //
    // Prints:
    // {{ lastName }} at line 1 did render Flynn as `Flynn`
    let data: [String: Any] = [
        "user": ["firstName": "Errol", "lastName": "Flynn"],
        "spy": logRenderings
    ]
    try! template.render(data)
    

    The string argument of DidRenderFunction is optional: it is nil if and only if the tag could not render because of a rendering error.

    Seealso

    WillRenderFunction

    Declaration

    Swift

    public typealias DidRenderFunction = (_ tag: Tag, _ box: MustacheBox, _ string: String?) -> Void
  • FilterFunction is the core type that lets GRMustache evaluate filtered expressions such as {{ uppercase(string) }}.

    You don’t use this type directly, and instead build filters with the Filter() function. For example:

    let increment = Filter { (x: Int?) in
        return x! + 1
    }
    

    To let a template use a filter, register it:

    let template = try! Template(string: "{{increment(x)}}")
    template.register(increment, forKey: "increment")
    
    // "2"
    try! template.render(["x": 1])
    

    Filter() can take several types of functions, depending on the type of filter you want to build. The example above processes Int values. There are three types of filters:

    • Values filters:

      • (MustacheBox) throws -> Any?
      • (T?) throws -> Any? (Generic)
      • ([MustacheBox]) throws -> Any? (Multiple arguments)
    • Pre-rendering filters:

      • (Rendering) throws -> Rendering
    • Custom rendering filters:

      • (MustacheBox, RenderingInfo) throws -> Rendering
      • (T?, RenderingInfo) throws -> Rendering (Generic)

    See the documentation of the Filter() functions.

    Declaration

    Swift

    public typealias FilterFunction = (_ box: MustacheBox, _ partialApplication: Bool) throws -> Any?
  • KeyedSubscriptFunction is used by the Mustache rendering engine whenever it has to resolve identifiers in expressions such as {{ name }} or {{ user.name }}. Subscript functions turn those identifiers into values.

    All types that expose keys to Mustache templates provide such a subscript function by conforming to the MustacheBoxable protocol. This is the case of built-in types such as NSObject, that uses valueForKey: in order to expose its properties; String, which exposes its length; collections, which expose keys like count, first, etc. etc.

    Your can build boxes that hold a custom subscript function. This is a rather advanced usage, supported by the low-level initializer MustacheBox(boolValue:value:keyedSubscript:filter:render:willRender:didRender:) -> MustacheBox.

    // A KeyedSubscriptFunction that turns "key" into "KEY":
    let keyedSubscript: KeyedSubscriptFunction = { (key: String) -> Any? in
        return key.uppercased()
    }
    
    // Render "FOO & BAR"
    let template = try! Template(string: "{{foo}} & {{bar}}")
    let box = MustacheBox(keyedSubscript: keyedSubscript)
    try! template.render(box)
    

    Missing keys vs. missing values.

    In order to express missing key, and have Mustache rendering engine dig deeper in the context stack in order to resolve a key, return nil.

    In order to express missing value, and prevent the rendering engine from digging deeper, return NSNull().

    Declaration

    Swift

    public typealias KeyedSubscriptFunction = (_ key: String) -> Any?