我正在尝试为我的视图进行动态布局


Yii, I am trying to have a dynamic layout for my views

我想用一个布局(sections.php)来渲染不同的视图,但是布局应该为每个视图加载不同的背景。我怎么能做到这一点,而不使用4种不同的布局为每个视图。

保护/视图/网站

    - - - - - - index . php
    ——about.php
    ——product.php
    ——brands.php
<保护/视图/布局/strong>
    ——sections.php

<html> 
   <head></head>
   <body>
      <div id= "viewname">
       <ul> 
          <li>Home</li>
          <li>about</li>
          <li>products</li>
          <li>brands</li>
       </ul>
       <!--I want to load different bg for this div for each view---> 
       <!--there's a lot of content that comes here, i dont want to do it in every page---> 
       <!--how can i load the class name for this div dynamically if possible-->
      </div>
      <div class=section-cont>
          <?php echo $content; ?>
      </div>
   </body>
</html>
我的css

#about
  {
    .... 
   background-image: ('../img/about.jpg')       
  }
#product
  {
    .... 
   background-image: ('../img/product.jpg')       
  }
#brands
  {
    .... 
   background-image: ('../img/brands.jpg')       
  }

myController

 class SiteController extends Controller
 {
   public function actionAbout()
   {
    $this->layout = "sections";
    $this->render('about');
   }
  //functions for other views is similar to above 

听起来像是你想根据页面改变背景。我这样做的方式不是为每个页面创建一个视图。在section布局中的类的body标签中设置一个变量。如:

<body class="<?php echo $body_class; ?>">

然后你就可以将body类从Controller Action传递到视图中。像这样:

$this->render('about',array('body_class'=> 'about-page'));

然后,您就可以通过瞄准CSS中的类来瞄准页面并更改背景图像。

希望对你有帮助。

编辑:问题需要传递变量到布局

对不起,我搞混了布局和视图文件。布局将访问$this,这将是当前控制器。因此,在控制器中如果你添加了一个公共属性/变量然后像这样编辑动作:

class SiteController extends Controller
{
    public $body_class;
    public function actionTest()
    {
        $this->layout = "testlayout";
        $this->body_class = 'test-page';
        $this->render('test');
    }

然后将布局文件中的body类或div类改为$this->body_class

注意:如果你喜欢的话,你也可以在页面视图中分配$this->body_class

如果我理解你的问题,你可以这样做。1.以当前页面名称为例。2.为每个页面存储另一个值。在你需要的地方调用这个类。

<?php
$page=basename($_SERVER['PHP_SELF']);
if($page == 'Home') {
 $css="#Home";
}
if($page == 'about') {
 $css="#about";
}
if($page == 'products') {
  $css="#product"; 
}
if($page == 'brands') {
  $css="#brands";
}
?>
<div  id="<?php echo $css ?>" class="section-cont"> </div>