Placeholders are a powerful way to include repeatedly used text snippets like company names, email addresses or phone numbers, but also dynamic stuff like galleries into your text fields. When you want to change this text snippet, you can do that in one place and it will automatically update in all places where the placeholder is used. It's also useful if these text snippets need a special styling or markup. Placeholders thus help you to keep information consistent and maintainable.
By default, such placeholders are wrapped in double curly braces like this:
If you want to use different start and end characters instead of the curly braces, you can control this using the
$end parameters of the
In your templates, you can replace such placeholders on the fly using the
This works great if you only need a few placeholders in a few limited places.
However, if you want to use placeholders all over the place, you don't want to repeat each replacement in every template. So how can we make this more versatile?
If you know in advance what text snippets you need and what they should be replaced with, you can define them in your configuration file:
With this in place, we can pass this array to the
Now, if we want to add additional placeholders, we can do that in the config.
But hey, this is still quite limited.
Maybe your editors would prefer to have control over the types of placeholders they need and what they should be replaced with. A structure field lends itself well to this purpose, and the
site.yml blueprint is a good place to define site-wide placeholders.
To get the array of options from this field, we create a
toOptions() field method in a plugin:
We can now get the replacement array from the field above like this:
Wouldn't it be nice to create our own field method and write it like this?:
… or connected to our structure field:
Let's put this in our plugin:
We can automate it even more, though. A hook replaces all the placeholders automatically, so that we don't even have to call our method in templates anymore:
For the final plugin, we want to get rid of some of the hardcoded stuff and leave it to the developer to decide where the replacements are defined, in the config or by the editor in a structure field, or even allow overriding/extending the replacements defined in
Config options for plugins should always follow the naming convention:
Now, we can control the behavior of the plugin through additional config options:
We can set some defaults in the configuration file and optionally replace or extend them with options from the placeholders field.
We can now even allow block level replacements and control them via an additional
block toggle field within the structure field definition:
If you rename the fields within the structure field or don't want to put the field into the site options, make sure to adapt the plugin code accordingly.