Laravel - @yield()不允许使用if [英] Laravel - @yield() not allowed in if

查看:699
本文介绍了Laravel - @yield()不允许使用if的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的标题中,我一直在使用@yield('title')为每个不同的页面创建一个动态标题。我想更进一步做这样的事情:

In my title I've been using @yield('title') for a while to create a dynamic title for every different page. I'd like to take it one step further and do something like this:

@if(@yield('title') == 'post') 
     <h1> This is the post page </h1>
@endif

但是,如果我尝试,我会收到错误:

But if I try that I get the error:

yield表达式只能在函数中使用

"The "yield" expression can only be used inside a function"

我搜索了一下,发现了类似于: :yield('title')但它们都不起作用。

I've searched around and found things like Section::yield('title') but they all didn't work.

如何在if语句中使用@yield('title')的值?
我知道你可以从控制器向视图发送一个$ title但是我觉得它看起来不太好......你必须两次定义标题。

How can I use the value of @yield('title') in an if statement? I know you can send a $title to the view from the controller but I dont think that looks very good.. You would have to define the title twice that way.

感谢阅读!

推荐答案

让我们来看看你的代码

@if(@yield('title') == 'post') 
 <h1> This is the post page </h1>
@endif

让我们假设它有效。那么 @section('title')会持有什么? 发表?它没有任何意义。

let's assume it works. then what does @section('title') will hold? Post? it doesn't make any sense.

@yield 用于替换该部分的内容。它不应该是有条件的。它不应该用作变量。它有特定的目的。无论你想使用哪种条件,都可以在视图或控制器中使用它。

@yield is used to replace the content of the section. it shouldn't be under conditional. it shouldn't be use as a variable. it has specific purpose. whatever conditionals you want to use, use it either in view or controller.

控制器:

return View::make('view.blade.php',['title' => 'post']);

就是这样。这就是你如何将var发送到视图。我认为这种做法没有任何问题。

that's it. that's how you send a var to the view. i din't see anything wrong with the approach.

对于laravel 4.1及以下版本,您可以使用此命令。

for laravel 4.1 and below, you could use this command.

@extends('layout.blade.php')->with('title','post')

但此行为已更改。直到4.1,传递给视图的变量无法在布局中访问。现在,在4.2中,此行为已更改,无论您传递给视图的数据是什么,它都存在于控制器中。

but this behavior has been changed. till 4.1, the vars passed to the view wasn't accessible in layout. now, in 4.2, this behavior is changed and whatever data you pass to the view, it is also present in the controller.

这篇关于Laravel - @yield()不允许使用if的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆