diff --git a/docs/custom-template-tags-and-filters.rst b/docs/custom-template-tags-and-filters.rst new file mode 100644 index 0000000..c34f343 --- /dev/null +++ b/docs/custom-template-tags-and-filters.rst @@ -0,0 +1,68 @@ +Custom Template Tags and Filters +================================ + +You can build your own custom filters and tags and pass them down while +rendering your template. Any custom filters or tags must be registered with a +namespace which contains all filters and tags available to the template. + +.. code-block:: swift + + let namespace = Namespace() + // Register your filters and tags with the namespace + let rendered = try template.render(context, namespace: namespace) + +Custom Filters +-------------- + +Registering custom filters: + +.. code-block:: swift + + namespace.registerFilter("double") { (value: Any?) in + if let value = value as? Int { + return value * 2 + } + + return value + } + +Registering custom filters with arguments: + +.. code-block:: swift + + namespace.registerFilter("multiply") { (value: Any?, arguments: [Any?]) in + let amount: Int + + if let value = arguments.first as? Int { + amount = value + } else { + throw TemplateSyntaxError("multiple tag must be called with an integer argument") + } + + if let value = value as? Int { + return value * 2 + } + + return value + } + +Custom Tags +----------- + +You can build a custom template tag. There are a couple of APIs to allow you to +write your own custom tags. The following is the simplest form: + +.. code-block:: swift + + namespace.registerSimpleTag("custom") { context in + return "Hello World" + } + +When your tag is used via ``{% custom %}`` it will execute the registered block +of code allowing you to modify or retrieve a value from the context. Then +return either a string rendered in your template, or throw an error. + +If you want to accept arguments or to capture different tokens between two sets +of template tags. You will need to call the ``registerTag`` API which accepts a +closure to handle the parsing. You can find examples of the ``now``, ``if`` and +``for`` tags found inside Stencil source code. diff --git a/docs/index.rst b/docs/index.rst index f2ebb30..d662b7c 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -39,3 +39,4 @@ Contents: templates builtins + custom-template-tags-and-filters