cakephp 的简单本地化问题

发布于 2025-01-01 06:13:30 字数 521 浏览 2 评论 0原文

我有一个包含两个字段的表,name 和 name_spa

要检索正确的语言,我必须在视图中执行类似的操作:

if($locale=='eng'){
  echo $var['Model']['name'];
}else{
  echo $var['Model']['name_spa'];
}

但是,我想做这样的操作:

echo $var['Model']['lname'][$locale];

我尝试使用虚拟字段,但这不起作用。我没有使用 i18n,因为它对于我的需要来说太复杂了。

public $virtualFields = array($lname => array(
                    'enh' => $this->name,
                    'spa' => $this->name_spa,
                ));

I have a table with two fields, name and name_spa

To retrieve the correct language, I have to do something like this in the view:

if($locale=='eng'){
  echo $var['Model']['name'];
}else{
  echo $var['Model']['name_spa'];
}

However, Id like to do something like this:

echo $var['Model']['lname'][$locale];

I tried using virtual fields but this didnt work. I didn't use i18n because it was way too complex for what I needed.

public $virtualFields = array($lname => array(
                    'enh' => $this->name,
                    'spa' => $this->name_spa,
                ));

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尘曦 2025-01-08 06:13:30

你的 virtualFields 数组对我来说似乎无效。正如其他人提到的,您不应该在您的视图中执行这些操作。一种选择可能是在 find() 之前构建 virtualFields 数组,如下所示:

在模型内部:

Public function findLocalized($id, $locale) {
     if ('spa' === $locale) {
         $this->virtualFields['name_localized'] = 'name_spa';
     } else {
        $this->virtualFields['name_localized'] = 'name';
     }

     return $this->find('first', array(
          'conditions' => array('id' => $id)
     ));
}

在控制器中,使用:

$this->set('var', $this->MyModel->findLocalized($id, $locale));

并在视图中使用:

echo $var['Model']['name_localized'];

这将输出所请求的 $locale 中的名称。

不过,您最好重新考虑您的本地化策略

Your virtualFields array seems invalid to me. As others mentioned, you should not be performing these things inside your view. One option might be to construct the virtualFields array just before the find(), something like:

Inside your model:

Public function findLocalized($id, $locale) {
     if ('spa' === $locale) {
         $this->virtualFields['name_localized'] = 'name_spa';
     } else {
        $this->virtualFields['name_localized'] = 'name';
     }

     return $this->find('first', array(
          'conditions' => array('id' => $id)
     ));
}

In your controller, use:

$this->set('var', $this->MyModel->findLocalized($id, $locale));

And use in view:

echo $var['Model']['name_localized'];

Which will outout the name in the requested $locale.

Still, you'd better rethink your strategy for localization

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文