代码之家  ›  专栏  ›  技术社区  ›  SaidbakR

CakePHP 2访问视图中定义的变量

  •  0
  • SaidbakR  · 技术社区  · 11 年前

    在两者中 我在一个名为 head 从调用 blog 布局:

    $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']);?>
    

    我使用上面的代码来定义或修改任意视图文件中的元标记值。这个 preMetaValues 被视为默认值。如果有 metaValues 在视图中定义,此代码将对其进行修改,并使 元值 准备使用。

    现在 具有 ,所描述的代码会生成以下错误:

    未能找到帮助程序类metaValuesHelper。

    错误:出现内部错误。

    事实上,我不知道CakePHP为什么把这个变量当作助手?我该如何解决这个问题?

    3 回复  |  直到 11 年前
        1
  •  1
  •   Alvaro    11 年前

    您可以通过设置控制器操作中的变量来完成此操作:

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

    然后在视图中,将其打印为:

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

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

    把它们当作任何其他变量来对待。

        2
  •  0
  •   Mindaugas Norvilas    11 年前

    为什么要使用$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']);?>
    
        3
  •  0
  •   Community CDub    7 年前

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

    因此,解决方案将取决于 set method of the view object 如下所示:

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

    也作为 Alvaro 在他的回答中,我必须访问那些没有$this的变量,即作为局部变量。

    这个答案的灵感来源于: Pass a variable from view to layout in CakePHP - or where else to put this logic?