在操作视图的开始或结束时呈现其他 html


Render additional html at the beginning or end of action view

我有Zend Framework MVC应用程序,其模块结构像上面这样:

/application
  /layouts
    /sripts
      /layout.phtml
  /modules
    /default
      /controllers
        /IndexController.php
        /OtherController.php
      /views
        /scripts
          /index
            /index.phtml
            /second.phtml
            /third.phtml
            /fourth.phtml
          /other
            /index.phtml
            /second.phtml
            /third.phtml
            /fourth.phtml

在我的布局.phtml中,我有一行

<div id="main">
    <?= $this->layout()->content ?>
</div>

我想将渲染的操作视图包装在 IndexController 和 OtherController 的每个操作中,除了第四个,使用一些代码,例如<div id='top'></div>在呈现的操作视图的开头,<div id='bottom'></div>在呈现的操作视图的末尾。我不想在每个操作视图 *.phtml 文件中手动执行此操作。在实际应用程序中有太多,除了代码看起来很混乱的解决方案。

怎么办?

在布局文件中,可以回显布局变量。这通常是我们放置由操作呈现的 html 的地方。您可以将多个操作的渲染追加到单个布局变量中,它们将按后进先出顺序显示。以下是将该变量插入布局文件的方式:

<?php echo $this->layout()->myLayoutVariable; ?>

您还可以在布局文件中设置占位符变量:

<?php echo $this->placeholder('myPlaceholderVariable'); ?>

然后,在其中一个视图文件中,您可以为此占位符变量提供 html 内容:

<?php
    $this->placeholder('myPlaceholderVariable')->append('<p>HTML GOES HERE</p>');
?>

如果未为占位符变量设置任何值,则布局文件中不会呈现任何内容。但是,如果您确实为该占位符变量设置了一个值,它将入到 html 中。

您可以仅为IndexControllerOtherController设置不同的布局:在每个控制器的init()方法中,可以添加以下内容:

Zend_Layout::getMvcInstance()->setLayout('some other layout');

试试这个:

$(document).ready(function(){
   $("#main").before(//insert header html here);
   $("#main").after(//insert footer html here);
});

我不确定你所说的第四个是什么意思,但如果你想针对特定的控制器/操作,你可以抓住 window.location.href 并让你的函数依赖于你想要查找的特定 URL。

希望有帮助。