【问题标题】:Symfony 1.4 Passing variables from action to viewSymfony 1.4 将变量从动作传递到视图
【发布时间】:2013-05-14 12:01:30
【问题描述】:

我是 Symfony 1.4 新手,我正在加入一个需要创建新仪表板的项目。

我在 analysis/actions/actions.class.php

中创建了以下控制器
public function executeTestDashboard(sfWebRequest $request){

    $foo = "FooBar";
    $this->foo = "ThisFooBar";
    return $this->renderPartial('analyse/testDashboard', array('foo' => $foo);

}

analysis/templates/_testDashboard.php 视图,这是 home/templates/indexSuccess.php 中包含的部分视图:

<div class="testDashboard">
        <h1>TEST</h1>
        <?php var_dump($foo);?>
</div>

它不起作用,$foo 既不是“FooBar”也不是“ThisFooBar”,而是“null”。我应该如何进行,以使其发挥作用? (或者甚至检查我的 executeTestDashboard 控制器是否已处理?)

【问题讨论】:

    标签: php symfony-1.4


    【解决方案1】:

    这里有几个例子可以更好地向你解释:

    // $foo is passed in TestDashboardSuccess.php, which is the default view rendered.
    public function executeTestDashboard(sfWebRequest $request)
    {
        $this->foo = "ThisFooBar";
    }
    
    // Different template indexSuccess.php is rendered. $foo is passed to indexSuccess.php
    public function executeTestDashboard(sfWebRequest $request)
    {
        $this->foo = "ThisFooBar";
        $this->setTemplate('index');
    }
    
    // Will return/render a partial, $foo is passed to  _testDashboard.php. This 
    // method is often used with ajax calls that just need to return a snippet of code
    public function executeTestDashboard(sfWebRequest $request)
    {
        $foo = 'ThisFooBar';
    
        return $this->renderPartial('analyse/testDashboard', array('foo' => $foo));
    }
    

    【讨论】:

      【解决方案2】:

      你应该阅读 Symfony 1.4 中的 partialscomponents。如果您使用include_partial() 在模板中包含部分内容,则只会呈现部分内容,不会执行任何控制器代码。

      如果您需要比简单渲染部分更多的逻辑,您应该使用一个组件,它看起来像:

      analyse/actions/compononets.class.php

      public function executeTestDashboard(){
      
          $this->foo = "FooBar: ".$this->getVar('someVar');
      }
      

      analyse/templates/_testDashboard.php

      <div class="myDashboard><?php echo $foo ?></div>
      

      在您希望显示仪表板的任何其他模板文件中:

      include_component('analyse', 'testDashboard', array('someVar' => $someValue));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-09
        • 2020-07-04
        • 2018-02-21
        • 1970-01-01
        • 1970-01-01
        • 2019-07-24
        • 2021-09-13
        相关资源
        最近更新 更多