Download the PHP package averay/tokenised-strings without Composer
On this page you can find all versions of the php package averay/tokenised-strings. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download averay/tokenised-strings
More information about averay/tokenised-strings
Files in averay/tokenised-strings
Package tokenised-strings
Short Description A lightweight system for rendering tokens in templated strings.
License MIT
Informations about the package tokenised-strings
Tokenised Strings
A lightweight system for rendering tokens in templated strings using a familiar syntax inspired by Jinja or Twig.
Motivation
The library aims to provide a more flexible substitute for PHP’s str_replace
function.
Manual string concatenation does not allow templating, and simple str_replace
substitutions offer limited functionality and require repetition. Meanwhile, a full templating engine such as Twig provides a lot of power at the cost of significantly increased complexity.
This library aims to fill a middle ground between the two options, allowing templates to be defined with a standard syntax and rendered throughout a system without needing to manage a full templating engine. The library is intended for rendering short tokens defined separately from where they are rendered, such as strings stored in configuration files or a database.
Syntax
The default configuration delimits tokens using double curly braces (e.g. {{ token_name }}
). Nested values can be accessed using periods (e.g. {{ parent.child }}
. Modifiers a.k.a. filters can be applied using pipes (e.g. {{ value | modifier }}
) and multiple can be applied. All whitespace between components is optional. The syntax is completely customisable (see below).
No in-template logic such as assignments, conditions, or loops are supported (i.e. any functionality Twig’s {% ... %}
tags provide), nor are comments.
Usage
The primary class provides a method for rendering templated strings, and two additional helper methods for rendering URLs and HTML:
A custom value formatter can be provided, which will be applied to each value when rendered in the template:
Global parameters can be defined, which will be available in all templates:
Global modifiers can also be defined, which will be available in all templates:
To define a custom syntax, the underlying Parser and Renderer classes can be used directly. In the following example, the custom syntax [% value->property >> modifier %]
is used:
A system may wish to move the configuration out to a global utility function, to allow rendering templates from anywhere in the same way str_replace
would be used: