【问题标题】:Laravel template not looping through array of viewsLaravel 模板没有遍历视图数组
【发布时间】:2013-05-26 05:09:48
【问题描述】:

希望这是我的某种愚蠢的疏忽,但我很难找到有关此或 Laravel 类似用法的其他示例的信息。我正在开发一个 Laravel 4 站点,其内容不是使用本地数据库填充,而是通过 Tumblr API 使用来自特定 Tumblr 博客的帖子。

每个 Tumblr 帖子都有与之关联的特定类型(“文本”、“视频”、“照片”等),并且每种类型都有完全不同类型的内容需要吐出,所以我有一个每个帖子类型的刀片模板,继承自主 post刀片模板。 (现在一切都只是一个存根。)

为了填写首页,在我的控制器中,我使用这些帖子视图 ($postViews) 填充了一个数组。令人抓狂的是,如果我遍历$postViews 并回显控制器中的每个单独视图,它包含正确的内容——数组中的所有三个视图都显示在它们内部的最终站点上正确的模板。

但是当我将$postViews 发送到我的welcome 视图,然后在其中循环遍历$postViews 时,它只呈现数组的第一个视图的三个实例。我不知道为什么。

这是相关代码。正如您在欢迎模板中看到的那样,我尝试使用原生 PHP 和 Laravel 模板语法在欢迎视图中循环遍历 $postViews。它们都表现出相同的行为:只显示三个帖子中的第一个,三次。

// controllers/HomeController.php

class HomeController extends BaseController {

    public function showIndex()
    {
        $client = new Tumblr\API\Client(CONSUMERKEY, CONSUMERSECRET);
        $tumblrData = (array) ($client->getBlogPosts(BLOGNAME));
        $postViews = array();

        foreach ($tumblrData['posts'] as $post) {
            $post = (array) $post;
            $type = TumblrParse::getPostType($post);
            $postViews[] = View::make('tumblr.'.$type, array('post' => $post));
        }
        foreach ($postViews as $p){
            echo $p; 
                    // This works! It displays each post view properly before
                    // before rendering the welcome view, but I need them to 
                    // be inside the welcome view in a specific place.
        }
        return View::make('home.welcome')->with('postViews', $postViews);
    }


// views/home/welcome.blade.php

@extends('layouts.master')
@section('title')
    @parent :: Welcome
@stop
@section('content')
    <h1>Hello World!</h1>
        <?php 
            foreach($postViews as $p) {
                echo $p; // Just outputs the first of the array three times
            }
        ?>
        @foreach($postViews as $p)
            {{ $p }} // Just outputs the first of the array three times
        @endforeach
@stop


// views/layouts/post.blade.php

<div class="post">
@yield('postcontent')
</div>


// views/tumblr/photo.blade.php
// Other post types have their own views: video.blade.php, text.blade.php, etc.

@extends('layouts.post')
@section('postcontent')
    <h1>This is a photo post!</h1>
    <?php var_dump($post); ?>
@stop

非常感谢任何帮助!我是 Laravel 的新手,我敢肯定这是显而易见的。据我所知,我通常在 PHP 中而不是在 Laravel 中做错。

【问题讨论】:

    标签: php model-view-controller laravel tumblr laravel-4


    【解决方案1】:

    在这种情况下,在使用视图渲染方法将每个视图附加到 $postViews 数组之前将其渲染为字符串可能是有意义的。

    $postViews[] = View::make('tumblr.'.$type, array('post' => $post))->render();
    

    【讨论】:

    • 做到了!既然您指出了这一点,那就完全有道理了。因为我让它们在其他上下文中正确呈现,所以我没有想到要寻找那个 View 方法。非常感谢!
    【解决方案2】:

    嵌套视图怎么样。检查文档。

    【讨论】:

    • 我查看了这个,但我没有看到任何将不同数据绑定到数组中每个项目的可能不同嵌套视图的示例。我确信这是可能的,但我没有运气。
    猜你喜欢
    • 2015-03-16
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    相关资源
    最近更新 更多