0

In both and I have used the following code snippet in an element named head called from the blog layout:

$this->preMetaValues = array(
    'title' => __('SiteTitle', true).' '.$title_for_layout,
    'desc' => Configure::read('siteTitle').', '.Configure::read('siteSlogan'),
    'keywords' => Configure::read('keywords'),
    'type' => 'article',
    'site_name' => __('SiteTitle', true),
    'imageURL' => $html->url('/img/logo.png', true)
);
if(!isset($this->metaValues)){
  $this->metaValues = $this->preMetaValues;
}
else{
  $this->metaValues = array_merge($this->preMetaValues, $this->metaValues);
}

<?php echo $html->meta('description',$this->metaValues['desc']); ?>
<?php echo $html->meta('keywords', $this->metaValues['keywords']);?>

I used the above code to define or modify meta-tags values from the any view file. The preMetaValues is regarded as the default values. If there is any metaValues defined in the view, this code will modify it and make the metaValues ready to be used.

Now with , the described code generates the following error:

Helper class metaValuesHelper could not be found.

Error: An Internal Error Has Occurred.

Indeed, I don't know why CakePHP regards this variable as helper? and how could I fix this issue?

4

3 回答 3

1

您可以通过从控制器操作中设置变量来做到这一点:

$this->set('title_for_layout', 'Your title');

然后在视图中,打印它:

<title><?php echo $title_for_layout?></title>

您在文档中有一个示例:http: //book.cakephp.org/2.0/en/views.html#layouts

只需将它们视为任何其他变量。

于 2013-09-18T12:41:57.977 回答
0

为什么要使用 $this 对象?你不能使用这样的简单解决方案:

$preMetaValues = array(
    'title' => __('SiteTitle', true).' '.$title_for_layout,
    'desc' => Configure::read('siteTitle').', '.Configure::read('siteSlogan'),
    'keywords' => Configure::read('keywords'),
    'type' => 'article',
    'site_name' => __('SiteTitle', true),
    'imageURL' => $html->url('/img/logo.png', true)
);
if(!isset($metaValues)){
  $metaValues = $preMetaValues;
}
else{
  $metaValues = array_merge($preMetaValues, $metaValues);
}

<?php echo $html->meta('description',$metaValues['desc']); ?>
<?php echo $html->meta('keywords', $metaValues['keywords']);?>
于 2013-09-18T13:59:35.180 回答
0

最后我找到了解决方案。它只是关于如何从视图中为布局设置变量。似乎在的早期版本中,视图是在布局之前处理的,而现在在中,布局是首先处理的,因此从视图中对布局中定义的任何变量的任何覆盖都不会成功。

因此,解决方案将取决于视图对象的set方法,如下所示:

//in some view such as index.ctp
    $this->set('metaValues', array(
                                   'title', 'The title string...',
                                   'desc' => 'The description string...'
                                   )
              );

同样正如Alvaro在他的回答中所认为的那样,我必须在没有 $this 的情况下访问这些变量,即作为局部变量。

这个答案的灵感来自:在 CakePHP 中将变量从视图传递到布局 - 或者在哪里放置这个逻辑?

于 2013-10-11T21:23:28.990 回答