dqqg0811 2015-11-12 04:16
浏览 38
已采纳

如何在Zend Framework 2中传递和显示变量

I want to learn Zend Framework 2, I already install it in my machine, I reached the welcome page, that's good, so when I look it's structure it has a big difference in CodeIgniter or Laravel, my problem is I want to display some text or string in my index.phtml. In my IndexController.php I got this.

public function indexAction() {
    $sample = 'sample string'; // this is what I want to pass in my index.phtml
    return new ViewModel();
}
  1. How can I pass the variable into my index.phtml ?
  2. How can I display it in my index.phtml?

For example, in CodeIgniter look like this.

//Controller.php
public function indexAction() {
    $data = 'Sample data'; // this is sample string that will display in my index.php
    return view('home',$data);
}
//View
<?php
   echo $data; // it will print the string in my $data(variable); 
?>

I'm newbie in Zend Framework 2, I don't have any idea in this framework. help me guys.
Thank you in advance for helping mo to solve my problem.

  • 写回答

1条回答 默认 最新

  • dougeqiang1619 2015-11-12 08:22
    关注

    In Zend 2, you pass any variable you want to use in your view to ViewModel or return an array:

    public function indexAction() {
        $sample = 'sample string'; // this is what I want to pass in my index.phtml
        return new ViewModel(array(
            "sample" => $sample
        ));
    }
    

    or:

    public function indexAction() {
        $sample = 'sample string'; // this is what I want to pass in my index.phtml
        return array(
            "sample" => $sample
        );
    }
    

    You can then access $sample in your index.phtml like this:

    <?php echo $this->sample ?>
    

    The array key will always be the property name of your view.

    For more information see also:

    http://framework.zend.com/manual/current/en/modules/zend.view.quick-start.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测