【问题标题】:Render additional html at the beginning or end of action view在动作视图的开头或结尾渲染额外的 html
【发布时间】:2012-05-29 02:30:42
【问题描述】:

我有 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

在我的 layout.phtml 中有一行

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

我想在 IndexController 和 OtherController 的每个动作中包装渲染的动作视图,除了第四个,用一些代码,比如&lt;div id='top'&gt;&lt;/div&gt;在开始,&lt;div id='bottom'&gt;&lt;/div&gt;在渲染动作视图的末尾。 我不想在每个操作视图 *.phtml 文件中手动执行此操作。实际应用中实在太多了,除了代码看起来乱七八糟的解决方案。

怎么做?

【问题讨论】:

标签: php model-view-controller zend-framework


【解决方案1】:

在布局文件中,您可以回显布局变量。这通常是我们放置动作呈现的 html 的地方。您可以将多个操作的渲染附加到单个布局变量中,它们将以 LIFO 顺序显示。下面是如何将该变量插入到布局文件中:

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

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

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

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

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • layout.phtml 中有太多的应用程序逻辑(我知道我不应该这样做)。让两个布局文件完成 99% 的相同工作是有问题的。我只需要在我的控制器 init() 中添加一些 prepend()、append() 和 wrap() 方法,但不知道任何...
    • 就像你不应该在layout.phtml 中拥有应用程序逻辑(就像你提到的那样),控制器不应该访问像prepend()append()wrap() 这样的东西,因为这些事情更具体到视图。如果您不想复制layout.phtml,我可以看到的另一种解决方案是将IndexControllerOtherController 中的$this-&gt;view 设置为扩展Zend_View 的内容,并在其中通过覆盖来包装您的输出render()...
    • 逻辑可能是一个太大的词,但有一些 cookie 处理和社交内容,现在我不想移动或复制 - 布局仍在变化。我通过检查 My_Controller 类中的模块、控制器和操作名称并将wrapper 决策变量分配给view 临时解决了这个问题。在 layout.phtml 条件语句中决定是否包装内容。感谢您的帮助。
    【解决方案3】:

    试试这个:

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

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

    希望对您有所帮助。

    【讨论】:

    • 在呈现应用程序内容时,我需要在 PHP 中执行此操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 2011-03-19
    • 2016-08-19
    • 1970-01-01
    相关资源
    最近更新 更多