问题描述
cakephp.org 上没有文档,我在 google 上也找不到.请给我链接一些文档或提供一份!
There is no documentation on cakephp.org and I am unable to find one on google. Please link me some documentation or supply one!
推荐答案
翻译行为是 CakePHP 的另一个非常有用但文档很少的特性.我已经按照以下方式在多语言网站中实施了几次,并取得了合理的成功.
The translate behavior is another of CakePHP's very useful but poorly documented features. I've implemented it a couple of times with reasonable success in multi-lingual websites along the following lines.
首先,翻译行为只会使您网站的数据库内容国际化.如果您有更多静态内容,您需要查看 Cake 的 __('string')
包装函数和 gettext
(有一些关于此的有用信息 此处)
Firstly, the translate behavior will only internationalize the database content of your site. If you've any more static content, you'll want to look at Cake's __('string')
wrapper function and gettext
(there's some useful information about this here)
假设我们要使用以下数据库表翻译内容:
Assuming there's Contents that we want to translate with the following db table:
CREATE TABLE `contents` (
`id` int(11) unsigned NOT NULL auto_increment,
`title` varchar(255) default NULL,
`body` text,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
content.php 模型有:
The content.php model then has:
var $actsAs = array('Translate' => array('title' => 'titleTranslation',
'body' => 'bodyTranslation'
));
在其定义中.然后,您需要将 i18n 表添加到数据库中:
in its definition. You then need to add the i18n table to the database thusly:
CREATE TABLE `i18n` (
`id` int(10) NOT NULL auto_increment,
`locale` varchar(6) NOT NULL,
`model` varchar(255) NOT NULL,
`foreign_key` int(10) NOT NULL,
`field` varchar(255) NOT NULL,
`content` mediumtext,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
然后,当您将数据保存到控制器中的数据库时,将区域设置设置为您想要的语言(此示例适用于波兰语):
Then when you're saving the data to the database in your controller, set the locale to the language you want (this example would be for Polish):
$this->Content->locale = 'pol';
$result = $this->Content->save($this->data);
这将在 i18n 表中为 pol 语言环境的标题和正文字段创建条目.Finds 将根据用户浏览器中设置的当前语言环境进行查找,返回一个数组,如:
This will create entries in the i18n table for the title and body fields for the pol locale. Finds will find based on the current locale set in the user's browser, returning an array like:
[Content]
[id]
[titleTranslation]
[bodyTranslation]
我们使用优秀的p28n组件来实现一种语言切换解决方案,该解决方案与 gettext 和翻译行为配合得很好.
We use the excellent p28n component to implement a language switching solution that works pretty well with the gettext and translate behaviours.
这不是一个完美的系统 - 因为它会动态创建 HABTM 关系,它可能会导致您手动创建的其他关系出现一些问题,但如果您小心,它可以很好地工作.
It's not a perfect system - as it creates HABTM relationships on the fly, it can cause some issues with other relationships you may have created manually, but if you're careful, it can work well.
这篇关于我如何在 CakePHP 中使用 TranslateBehavior?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!