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 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 missing something? Any recommended workarounds?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
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 extendsExtension
: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 classTextFormatter
" which will make our newNL2BR
function available on allText
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 thanHTMLText
as a previous answer has assumed. If you are usingHTMLText
you can simply extend that class instead by changing yourextensions.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:
Then call it in your template:
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:
Add the following to your _config.php file:
Then you can call it in you template like so:
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
andVarchar
database fields are automatically converted usingnl2br()
.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 aTextareaField
).Hopefully this helps future visitors!