API reference

Public API definition

This page contains information about types that are part of Cottle’s public API.

Warning

Types not listed in this page should not be considered as part of the public API, and are not taken into consideration when changing version number (see section Versioning convention).

Warning

You should avoid relying on method behaviors not documented in this page as they could change from one version to another.

Compiled documents

class IDocument

A document in Cottle is a compiled template, which means a template converted to an optimized in-memory representation.

Value Render (IContext context, IO.TextWriter writer)

Render document and write output to given IO.TextWriter instance. Return value is the value passed to top-level return command if any, or an undefined value otherwise.

String Render (IContext context)

Render document and return outout as a String instance.

class Document

Methods from this static class must be used to create instances of DocumentResult.

DocumentResult CreateDefault (IO.TextReader template, DocumentConfiguration configuration = default)

Create a new default IDocument instance suitable for most use cases. Template is read from any non-seekable IO.TextWriter instance.

DocumentResult CreateDefault (String template, DocumentConfiguration configuration = default)

Create a new default IDocument instance similar to previous method. Template is read from given String instance.

DocumentResult CreateNative (IO.TextReader template, DocumentConfiguration configuration = default)

Create a new native IDocument instance for better rendering performance but higher compilation cost. Template is read from any non-seekable IO.TextWriter instance. See section Native documents for details about native documents.

DocumentResult CreateNative (String template, DocumentConfiguration configuration = default)

Create a new native IDocument instance similar to previous method. Template is read from given String instance.

class DynamicDocument
: Cottle.IDocument

Deprecated class, use Cottle.Document.CreateNative to create native documents.

class SimpleDocument
: Cottle.IDocument

Deprecated class, use Cottle.Document.CreateDefault to create documents.

class DocumentConfiguration

Document configuration options, can be passed as an optional argument when creating a new document.

String BlockBegin { get; set; }

Delimiter for start of command, see section Delimiters customization for details.

String BlockContinue { get; set; }

Delimiter for continue command, see section Delimiters customization for details.

String BlockEnd { get; set; }

Delimiter for end of command, see section Delimiters customization for details.

Nullable<char> Escape { get; set; }

Delimiter for escape, see section Delimiters customization for details. Default escape character is \ when this property is null.

Boolean NoOptimize { get; set; }

Disable code optimizations after compiling a document, see Optimizer deactivation for details.

Func<String, String> Trimmer { get; set; }

Function used to trim unwanted character out of plain text when parsing a document, see section Plain text trimming for details.

class DocumentResult

This structure holds result of a template compilation, which can either be successful and provide compiled IDocument instance or failed and provide compilation error details as a list of DocumentReport elements:

IDocument Document { get; }

Instance of compiled document, only if compilation was successful (see DocumentResult.Success).

IReadOnlyList<DocumentReport> Reports { get; }

List of anomalies detected during compilation, as a read-only list of DocumentReport items.

Boolean Success { get; }

Indicate whether compilation was successful or not.

IDocument DocumentOrThrow { get; }

Helper to return compiled document when compilation was successful or throw a Exceptions.ParseException exception with details about first compilation error otherwise.

class DocumentReport

Anomaly report on compiled template, with references to related code location.

Int32 Length { get; }

Length of the last lexem recognized when encountering an anomaly.

String Message { get; }

Human-readable description of the anomaly. This value is meant for being displayed in a user interface but not processed, as its contents is not predictable.

Int32 Offset { get; }

Offset of the last lexem recognized when encountering an anomaly.

DocumentSeverity Severity { get; }

Report severity level.

enum DocumentSeverity

Report severity level.

Error

Template issue that prevents document from being constructed.

Warning

Template issue that doesn’t prevent document from being constructed nor rendered, but may impact rendered result or performance and require your attention.

Notice

Template issue with no visible impact, mostly used for code suggestions or deprecation messages.

Rendering contexts

class IContext

This interface is used to pass variables to a document when rendering it.

Value this[, Value symbol] { get; }

Get variable by its symbol (usually its name), or an undefined value if no value was defined with this name.

class Context

Methods from this static class must be used to create instances of IContext.

IContext CreateBuiltin (IContext custom)

Create a rendering context by combining a given existing context with all Cottle built-in functions (see section Built-in functions). Variables from the input context always have priority over built-in functions in case of collision.

IContext CreateBuiltin (IReadOnlyDictionary<Value, Value> symbols)

Create a rendering context by combining variables from given dictionary with all Cottle built-in functions. This method is similar to previous one and only exists as a convenience helper.

IContext CreateCascade (IContext primary, IContext fallback)

Create a rendering context by combining two existing contexts that will be searched in order when querying a variable. Primary context is searched first, then fallback context is searched second if the result from first one was an undefined value.

IContext CreateCustom (Func<Value, Value> callback)

Create a rendering context using given callback for resolving variables. Callback must always expected to return a non-null result, possibly an undefined value.

IContext CreateCustom (IReadOnlyDictionary<Value, Value> symbols)

Create a rendering context from given variables dictionary.

(IContext,ISymbolUsage) CreateMonitor (IContext context)

Wrap given context inside a monitoring context to get statistics on which variables are read from it. Output IContext is the monitored one that should be passed to document, while the ISymbolUsage usage is the structure you can query after rendering the document to get information about which variables were read.

Function declaration

class IFunction

Cottle function interface.

Boolean IsPure { get; }

Indicates whether function is pure or not. Pure functions have no side effects nor rely on any, and are eligible to various rendering optimizations.

Value Invoke (Object state, IReadOnlyList<Value> arguments, IO.TextWriter output)

Invoke function with given arguments. Variable state is a opaque payload that needs to be passed to nested function calls if any, arguments contains the ordered list of values passed to function, and output is a text writer to document output result.

class Function

Methods from this static class must be used to create instances of IFunction.

IFunction Create (Func<Object, IReadOnlyList<Value>, IO.TextWriter, Value> callback, Int32 min, Int32 max)

Create a non-pure function accepting between min and max arguments (included).

IFunction Create (Func<Object, IReadOnlyList<Value>, IO.TextWriter, Value> callback, Int32 count)

Create a non-pure function accepting exactly count arguments.

IFunction Create (Func<Object, IReadOnlyList<Value>, IO.TextWriter, Value> callback)

Create a non-pure function accepting any number of arguments.

IFunction Create0 (Func<Object, IO.TextWriter, Value> callback)

Create a non-pure function accepting zero argument.

IFunction Create1 (Func<Object, Value, IO.TextWriter, Value> callback)

Create a non-pure function accepting one argument.

IFunction Create2 (Func<Object, Value, Value, IO.TextWriter, Value> callback)

Create a non-pure function accepting two arguments.

IFunction Create3 (Func<Object, Value, Value, Value, IO.TextWriter, Value> callback)

Create a non-pure function accepting three arguments.

IFunction CreatePure (Func<Object, IReadOnlyList<Value>, Value> callback, Int32 min, Int32 max)

Create a pure function accepting between min and max arguments (included).

IFunction CreatePure (Func<Object, IReadOnlyList<Value>, Value> callback, Int32 count)

Create a pure function accepting exactly count arguments.

IFunction CreatePure (Func<Object, IReadOnlyList<Value>, Value> callback)

Create a pure function accepting any number of arguments.

IFunction CreatePure0 (Func<Object, Value> callback)

Create a pure function accepting zero argument.

IFunction CreatePure1 (Func<Object, Value, Value> callback)

Create a pure function accepting one argument.

IFunction CreatePure2 (Func<Object, Value, Value, Value> callback)

Create a pure function accepting two arguments.

IFunction CreatePure3 (Func<Object, Value, Value, Value, Value> callback)

Create a pure function accepting three arguments.

Value declaration

class Value

Cottle values can hold instances of any of the supported types (see section Value types).

Value EmptyMap { get; }

Static and read-only empty map value, equal to Value.FromEnumerable(new Value[0]).

Value EmptyString { get; }

Static and read-only empty string value, equal to Value.FromString(string.Empty).

Value False { get; }

Static and read-only boolean “false” value, equal to Value.FromBoolean(false).

Value True { get; }

Static and read-only boolean “true” value, equal to Value.FromBoolean(true).

Value Undefined { get; }

Static and read-only undefined value, equal to new Value() or default(Value).

Value Zero { get; }

Static and read-only number “0” value, equal to Value.FromNumber(0).

Boolean AsBoolean { get; }

Read value as a boolean after converting it if needed. Following conversion is applied depending on base type:

  • From numbers, return true for non-zero values and false otherwise.
  • From strings, return true for non-zero length values and false for empty strings.
  • From undefined values, always return false.
IFunction AsFunction { get; }

Read value as a function, only if base type was already a function. No conversion is applied on this property, and return value is undefined if value was not a function.

Double AsNumber { get; }

Read value as a double precision floating point number after converting it if needed. Following conversion is applied depending on base type:

  • From booleans, return 0 for false or 1 for true.
  • From strings, parse double number if value matches regular expression [0-9]*(\\.[0-9]+)?, or 0 otherwise.
  • From undefined values, always return 0.
String AsString { get; }

Read value as a string after converting it if needed. Following conversion is applied depending on base type:

  • From booleans, return string "true" for true and empty string otherwise.
  • From numbers, return result of call to double.ToString() method with invariant culture.
  • From undefined values, always return an empty string.
IMap Fields { get; }

Get child field of current value if any, or an empty map otherwise.

ValueContent Type { get; }

Get base type of current value instance.

FromBoolean (Boolean value)

Create value from given boolean instance.

FromDictionary (IReadOnlyDictionary<Value, Value> dictionary)

Create a map value from given keys and associated value in given dictionary, without preserving any ordering. This override assumes input dictionary is immutable and simply keeps a reference on it without duplicating the data structure.

FromDictionary (IDictionary<Value, Value> dictionary)

Create a map value from given keys and associated value in given dictionary, without preserving any ordering. This override assumes input dictionary is mutable and duplicates the data structure to avoid further modifications.

FromEnumerable (IEnumerable<KeyValuePair<Value, Value>> pairs)

Create a map value from given elements, preserving element ordering but also allowing O(1) access to values by key.

FromEnumerable (IEnumerable<Value> elements)

Create a map value from given elements. Numeric keys are generated for each element starting at index 0.

FromFunction (IFunction function)

Create a function value by wrapping an executable IFunction instance. See sections Function declaration and Native .NET functions for details about functions in Cottle.

FromGenerator (Func<Int32, Value> generator, Int32 count)

Create map value from given generator. Generator function generator is used to create elements based on their index, and the map will contain count values associated to keys 0 to count - 1. Values are created only when retrieved, so creating a generator value with 10000000 elements won’t have any cost until you actually access these elements from your template.

FromLazy (Func<Value> resolver)

Create a lazy value from given value resolver. See section Lazy value evaluation for details about lazy value resolution.

FromMap (IMap value)

Create value from given IMap instance.

FromNumber (Double value)

Create value from given double instance.

FromReflection<TSource> (TSource source, Reflection.BindingFlags bindingFlags)

Create a reflection-based value to read members from object source. Source object fields and properties are resolved using Type.GetFields and Type.GetProperties methods and provided binding flags for resolution. See section Reflection values for details about reflection-based inspection.

FromString (String value)

Create value from given string instance.

class FunctionValue
: Cottle.Value

Deprecated class, use Value.FromFunction to create function values.

FunctionValue (IFunction function)

Class constructor.

class LazyValue
: Cottle.Value

Deprecated class, use Value.FromLazy to create lazy values.

LazyValue (Func<Value> resolver)

Class constructor.

class ReflectionValue
: Cottle.Value

Deprecated class, use Value.FromReflection to create reflection values.

ReflectionValue (Object source, Reflection.BindingFlags binding)

Class constructor with explicit binding flags.

ReflectionValue (Object source)

Class constructor with default binding flags for resolution (public + private + instance).

class IMap

Value fields container.

Value this[, Value key] { get; }

Get field by its key (usually its name), or an undefined value if no field was defined with this name.

Int32 Count { get; }

Get number of fields contained within this value.

Boolean Contains (Value key)

Check whether current map contains a field with given key or not. Returns true if map contains requested field or false otherwise.

Boolean TryGet (Value key, out Value value)

Try to read field by key. Returns true and set output Value instance if found, or return false otherwise.

enum ValueContent

Base value type enumeration.

Boolean

Boolean value, either true or false.

Function

Invokable function value.

Map

Enumerable key/value collection.

Number

Numeric value, either integer or floating point.

String

Characters string value.

Void

Undefined value.

Exceptions

class ParseException
: Exception

Exception class raised when trying to convert an invalid template string into a IDocument instance.

String Lexem { get; }

Lexem (text fragment) that was unexpectedly encountered in template.

Int32 LocationLength { get; }

Length of the last lexem recognized when encountering a parsing error.

Int32 LocationStart { get; }

Offset of the last lexem recognized when encountering parsing error.