2016-12-14 79 views
2

URLSegmentFilter有一个静态数组$default_replacements持有,除其他外,字符串&符号转换(从&到- 和 -)的网址。SilverStripe覆盖URLSegmentFilter静态

我想扩展类并覆盖此静态到翻译的符号转换(仅适用于为英文)。

我该如何为这个目标覆盖所有者静态?

class URLSegmentFilterExtension extends Extension { 

    private static $default_replacements = array(
     '/&/u' => '-and-', // I need to translate this using _t() 
     '/&/u' => '-and-', // And this one 
     '/\s|\+/u' => '-', 
     '/[_.]+/u' => '-', 
     '/[^A-Za-z0-9\-]+/u' => '', 
     '/[\/\?=#]+/u' => '-', 
     '/[\-]{2,}/u' => '-', 
     '/^[\-]+/u' => '', 
     '/[\-]+$/u' => '' 
    ); 

} 

回答

1

首先:在URLSegmentFilter主要经营在CMS背景下,你通常只是有一个单一的区域(取决于编辑成员的设置)。所以单独使用_t()可能不是很有帮助?因此,您可能必须获取当前的编辑区域设置(假设您使用Fluent或Translatable)并且暂时设置区域设置以进行翻译。

我没有看到通过Extension在翻译中挂钩的方法。我认为你最好创建一个自定义子类并通过Injector使用它。

像这样的东西应该工作:

<?php 
class TranslatedURLSegmentFilter extends URLSegmentFilter 
{ 
    public function getReplacements() 
    { 
     $currentLocale = i18n::get_locale(); 
     $contentLocale = Translatable::get_current_locale(); 
     // temporarily set the locale to the content locale 
     i18n::set_locale($contentLocale); 

     $replacements = parent::getReplacements(); 
     // merge in our custom replacements 
     $replacements = array_merge($replacements, array(
      '/&amp;/u' => _t('TranslatedURLSegmentFilter.UrlAnd', '-and-'), 
      '/&/u' => _t('TranslatedURLSegmentFilter.UrlAnd', '-and-') 
     )); 

     // reset to CMS locale 
     i18n::set_locale($currentLocale); 
     return $replacements; 
    } 
} 

然后,你必须通过配置,使定制URLSegmentFilter通过把这样的事情在你的mysite/_config/config.yml文件:

Injector: 
    URLSegmentFilter: 
    class: TranslatedURLSegmentFilter 

更新:以上示例假定您使用的模块为Translatable。如果您使用流利,替换以下行:

$contentLocale = Translatable::get_current_locale(); 

有:

$contentLocale = Fluent::current_locale(); 
+0

感谢您的输入bummzack动态更新配置。虽然我不使用任何翻译模块。我想在CMS语言环境中进行翻译,每个用户可能会有所不同。 – Faloude

+0

@Faloude这似乎不合逻辑?因此,如果一个Admin具有'en'作为区域设置,他将在URL中保存带有“-and-'的页面,而另一个使用'de'登录的管理员将生成包含'-und-'的URL?对于前端用户,这将导致混合类型的URL,具体取决于谁保存了页面?这不可能是你想要的...... – bummzack

+0

在任何情况下,将我提议的解决方案改为在没有翻译模块的情况下工作应该非常简单。只需删除不需要的代码行,即可设置。 – bummzack

1

可以在mysite/_config.php

$defaultReplacements = Config::inst()->get('URLSegmentFilter', 'default_replacements'); 

$translatedAnd = _t('URLSegmentFilter.And','-and-'); 
$defaultReplacements['/&amp;/u'] = $translatedAnd; 
$defaultReplacements['/&/u'] = $translatedAnd; 

Config::inst()->Update('URLSegmentFilter', 'default_replacements', $defaultReplacements); 
+0

无需翻译mod即可工作这并不真正启用翻译...只是最初将值设置为其他内容。由于在从CMS内保存页面时会生成URL,因此您必须动态更改该值,具体取决于CMS中的内容区域设置。 – bummzack

+0

@bummzack我同意你的意见。但是,您可以重复使用具有预设区域设置(使用_ss_environment.php)的不同语言安装(许多域)的相同代码。 –

+0

的确如此,但是你可以直接替换配置中的值,并且根本不用麻烦'_t'? – bummzack