【问题标题】:Yii, I am trying to have a dynamic layout for my viewsYii,我正在尝试为我的视图设置动态布局
【发布时间】:2015-10-10 17:40:11
【问题描述】:

我希望使用一个布局(sections.php)呈现不同的视图,但布局应该为每个视图加载不同的背景。在不为每个视图使用 4 种不同布局的情况下如何实现这一点。

受保护/观看次数/网站

    - index.php
    - 关于.php
    - 产品.php
    -brands.php
受保护/视图/布局
    -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')       
  }

我的控制器

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

【问题讨论】:

  • Yii.我投降。 _

标签: php html css yii


【解决方案1】:

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

<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-&gt;body_class

注意:如果您愿意,也可以在页面视图中指定 $this-&gt;body_class

【讨论】:

  • 我正在更改 div 的背景,而该 div 仅在布局文件中而不是视图文件中,您可以将变量发送到布局文件吗?
  • @YungA 编辑了我的原始评论以回答问题以获得更好的格式。
  • 哇..非常感谢老兄。你给了最好的答案。我从没想过布局文件可以访问$this 或当前控制器
【解决方案2】:

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

<?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>

【讨论】:

    猜你喜欢
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    相关资源
    最近更新 更多