2017-01-09 36 views
1

我在Laravel 5.3中使用刀片模板。我想呈现两个列表 - “朋友”和“熟人”之一。列表的页眉和页脚在这两种情况下都是相同的,但在朋友列表中呈现的项目与在熟人列表中呈现的项目具有不同的格式和字段。在具有相同父级布局的@each伪指令中使用不同的子视图

下面是在我的控制器两种方法:

public function showFriends() { 
    return view('reports.friends', ['profiles' => $friends]); 
} 

public function showAcquaintances() { 
    return view('reports.acquaintances', ['profiles' => $acquaintances']); 
} 

这里是我的刀模板:

// reports/acquaintances.blade.php 
<div>Some generic header HTML</div> 
<div class="container"> 
    @each('reports.acquaintance', $profiles, 'profile') 
</div> 
<div>Some generic footer HTML</div> 

// reports/acquaintance.blade.php 
<div class="media"> 
    <div>Some HTML formatting specific to acquaintance item</div> 
    {{ $profile->name }} 
    {{ $profile->job }} 
</div> 

// reports/friends.blade.php 
<div>Some generic header HTML</div> 
<div class="container"> 
    @each('reports.friend', $profile, 'profile') 
</div> 
<div>Some generic footer HTML</div> 

// reports/friend.blade.php 
<div class="media"> 
    <div>Some HTML formatting specific to friend item</div> 
    {{ $profile->name }} 
    {{ $profile->birthday }}  
</div> 

这似乎不是要达到我想要什么,因为一个非常有效的方法我必须为我的列表创建两个完全相同的父模板:friends.blade.php和acquaintances.blade.php。我真正需要的是能够拥有一个通用的父模板,然后以某种方式在我的控制器中指定我想用来呈现列表项的模板。这可能吗?是否有另一种更优雅的方式来实现这一点?我刚刚开始让我的脑袋绕过Blade,任何指针都会非常感激。

回答

1

您可以将其分为通用persons_list和两个自定义项目。然后用列表的条件内:

public function showFriends() { 
    return view('reports.persons_list', ['profiles' => $friends, 'type' => 'friends']); 
} 

public function showAcquaintances() { 
    return view('reports.persons_list', ['profiles' => $acquaintances, 'type' => 'acquaintances']); 
} 

和刀片:

// reports/persons_list.blade.php 
<div>Some generic header HTML</div> 
<div class="container"> 

    @if ($type == 'friends') 

     @each('reports.friend', $profiles, 'profile') 

    @else 

     @each('reports.acquaintance', $profiles, 'profile') 

    @endif 

</div> 
<div>Some generic footer HTML</div> 
+0

感谢@ SERG-chernata。这非常合理。我有一些模糊的想法,我可能能够引用我想直接在view()调用中使用的子模板,但是如果条件是最优雅的方式,那就这样吧。 –

+0

非常欢迎。只要有机会,请接受答案。 :) –

相关问题