K. Hallman K. Hallman - 1 year ago 82
PHP Question

Is it possible to run a function on a Silverstripe template variable to format output?

I've created a data model that includes a plain textarea entry field for an office address. I would like to do the equivalent of

when printing the data in my relevant Silverstripe template. As far as I can tell, their templating system does not support such functionality.

Am I missing something? Any recommended workarounds?

Answer Source

In Silverstripe 3 this would be best achieved by creating a DataExtension class (as opposed to overriding the class). (Note: this would be possible in 2.4.x as well, but the code would be quite different.)

Create a new class called TextFormatter which extends Extension:

class TextFormatter extends Extension { 
    public function NL2BR() {
        return nl2br($this->owner->value);

Specify in config that the Text class should be extended with your brand new class. This can be done either in your _config.php file or (preferably) in a YAML file.

If you don't already have one, create a new file at mysite/_config/extensions.yml with the following content (or you can append this to your existing file):


This just says "extend the class Text with the class TextFormatter" which will make our new NL2BR function available on all Text objects.

Now, in your templates you can simply call $OfficeAddr.NL2BR and the output will be run through your function before being output.

Note that I've assumed your model uses Text as the field type rather than HTMLText as a previous answer has assumed. If you are using HTMLText you can simply extend that class instead by changing your extensions.yml file as appropriate.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download