Symfony变量从动作传递到视图

时间:2010-09-03 06:20:35

标签: php model-view-controller symfony1

您好我有以下问题:

我在Symfony,action.class.php中有一个视图的动作类,在那里我有这个代码:

foreach ($images as $i => $img)
 {
   if (strstr($request->getFileType($img), 'image'))
   {
     $enter = true; 
     $name = Util::processImages($request, $img, 'app_uploads_temp_dir');

     if ($name != '')
     {
        $userimages[$i] = $name;
        $this->uploads[$i] = true;
        $this->message = 'Image loaded';
     }
   }
}

在我看来,我希望根据具体情况呈现上传字段或消息:

<div class="fotoupload">
   <?php if ( !isset($this->uploads[1]) ): ?>
   <?php echo label_for('photosec1', 'Imagen 2:') ?>
   <?php echo input_file_tag('photosec1') ?>
   <?php else: ?>
   <span><?php $this->message ?></span>
   <?php endif ?>
</div>

但$ this-&gt;消息未设置,$ message或从动作传递的任何变量都没有,有人能告诉我为什么会发生这种情况,我该如何解决?

2 个答案:

答案 0 :(得分:2)

好的大家,我自己找到了答案,对不起发布答案,我会留下来以防有人遇到同样的问题:

整个想法是使用插槽,代码将是这样的:

foreach ($images as $i => $img)
 {
   if (strstr($request->getFileType($img), 'image'))
   {
     $enter = true; 
     $name = Util::processImages($request, $img, 'app_uploads_temp_dir');

     if ($name != '')
     {
        $userimages[$i] = $name;
        $uploads[$i] = true;
        $message = 'Image loaded';
     }
   }
}

$this->getResponse()->setSlot("message", $message);

并在下一个代码中,使用变量:

   <span><?php echo get_slot("message") ?></span>

非常感谢!

  • 如果管理员认为应该删除此问题,请告诉我,我会这样做

答案 1 :(得分:2)

如果您在操作中设置了$ this-&gt;消息,则视图中会显示为$ message。

但在您的情况下,您在foreach()中设置了$ this-&gt;消息,因此您为每个循环重新定义$ this-&gt;消息。这可能解释了为什么$ message没有返回您期望的值。

在这里使用插槽不是正确的用例,因为所有$ this-&gt;在动作中设置的变量已经直接传递给视图/模板。