TemplateProcessor

public class TemplateProcessor

Utility to replace double brace wrapped text with values extracted from a DataObject.

  • Processes the input text looking for all occurrences of double brace wrapped text: {{ }}

    The format of text inside the braces can be as follows:

    • a valid json path style string: e.g. {{container.key}}
    • a valid json path style string with an optional fallback: e.g. {{container.key || fallback}}
      • in the event that container.key is not available in the context object, the fallback will be used

    All occurrences of the templating {{ }} will be replaced with either the value from the context object according to the json path specified, or the fallback string if provided, else a blank string ""

    Declaration

    Swift

    public class func process(text: String, context: DataObject) -> String

    Parameters

    text

    the String to process for {{ }} substitution block

    context

    the DataObject to extract values from

    Return Value

    A new string with all substitution blocks replaced

  • Compiles the input text into a reusable Template, scanning once to split the source into plain-text and substitution sections. The substitution paths it references are collected ahead of time (see Template.substitutions).

    This lets callers learn up-front which values a context needs to provide - so (potentially slow) work to populate the context can be limited to only the required data - before processing the template against one or more contexts via Template.process(context:).

    Each substitution block follows the same rules as process(text:context:).

    Declaration

    Swift

    public class func compile(_ text: String) -> Template

    Parameters

    text

    the String to compile, looking for {{ }} substitution blocks.

    Return Value

    A compiled Template.