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 nl2br($OfficeAddr)
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 m开发者_JAVA技巧issing something? Any recommended workarounds?
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):
Text:
extensions:
['TextFormatter']
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.
IMPORTANT: This solution is applicable to SilverStripe 2.X. If you're using SilverStripe 3.0 - see SS3.0 answer on this page.
You'd simply add a getter to your model:
public function FormattedAddress {
return nl2br($this->OfficeAddr);
}
Then call it in your template:
<p>$FormattedAddress</p>
OR - if you want to adhere to MVC, the more complex solution is...
Assuming you've used the HTMLText field type you could extend the HTMLText class:
Create a file called - Extended_HTMLText.php (or something similar) - add the following to it and save it into your code directory:
class Extended_HTMLText extends HTMLText {
function NL2BR() {
return nl2br($this->value);
}
}
Add the following to your _config.php file:
Object::useCustomClass('HTMLText', 'Extended_HTMLText', true);
Then you can call it in you template like so:
<p>$OfficeAddr.NL2BR</p>
This at least takes your view logic out of your model ;)
This has been fixed in SilverStripe 3 (since May 2013) which all of these answers predate. Moving forward now, all Text
and Varchar
database fields are automatically converted using nl2br()
.
So ... If you're silly like me and you ended up here, note that there's a possibility that you're actually outputting an HTMLText
field but thought you were using plain text (because maybe you setup ->getCMSFields()
with a TextareaField
).
Hopefully this helps future visitors!
精彩评论