是否可以在Silverstripe模板变量上运行函数以格式化输出? [英] Is it possible to run a function on a Silverstripe template variable to format output?

查看:45
本文介绍了是否可以在Silverstripe模板变量上运行函数以格式化输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个数据模型,其中包括用于办公地址的纯文本区域输入字段.在相关的Silverstripe模板中打印数据时,我想做 nl2br($ OfficeAddr)的等效操作.据我所知,他们的模板系统不支持这种功能.

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?

推荐答案

在Silverstripe 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.)

创建一个名为 TextFormatter 的新类,该类扩展了 Extension :

Create a new class called TextFormatter which extends Extension:

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

在配置中指定 Text 类应使用您的全新类扩展.可以在您的 _config.php 文件中,也可以(最好)在YAML文件中.

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.

如果还没有,请在 mysite/_config/extensions.yml 中创建一个新文件,其内容如下(或者您可以将其附加到现有文件中):

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']

这只是说将类 Text 扩展为类 TextFormatter ",这将使我们的新 NL2BR 函数可用于所有文字对象.

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

现在,您可以在模板中简单地调用 $ OfficeAddr.NL2BR ,输出将通过函数运行,然后输出.

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

请注意,我假设您的模型使用 Text 作为字段类型,而不是先前假定的 HTMLText .如果您使用的是 HTMLText ,则可以通过适当地更改 extensions.yml 文件来简单地扩展该类.

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.

这篇关于是否可以在Silverstripe模板变量上运行函数以格式化输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆