Laravel - Check if @yield empty or not

匿名 (未验证) 提交于 2019-12-03 01:31:01

问题:

Is it possible to check into a blade view if @yield have content or not?

I am trying to assign the page titles in the views:

@section("title", "hi world") 

So I would like to check in the main layout view... something like:

 Sitename.com {{ @yield('title') ? ' - '.@yield('title') : '' }} 

回答1:

There is probably a prettier way to do this. But this does the trick.

@if (trim($__env->yieldContent('title')))     

@yield('title')

@endif


回答2:

In Laravel 5 we now have a hasSection method we can call on a View facade.

You can use View::hasSection to check if @yeild is empty or not:

     @if(View::hasSection('title'))         @yield('title')     @else         Static Website Title Here     @endif 

This conditional is checking if a section with the name of title was set in our view.

Tip: I see a lot of new artisans set up their title sections like this:

@section('title') Your Title Here @stop 

but you can simplify this by just passing in a default value as the second argument:

@section('title', 'Your Title Here') 

The hasSectionmethod was added April 15, 2015.



回答3:

Given from the docs:

@yield('section', 'Default Content'); 

Type in your main layout e.g. "app.blade.php", "main.blade.php", or "master.blade.php"

{{ config('app.name') }} - @yield('title', 'Otherwise, DEFAULT here')

And in the specific view page (blade file) type as follows:

@section('title') My custom title for a specific page @endsection 


回答4:

For those looking on it now, you can use :

@hasSection('name')    @yield('name') @endif 

See : https://laravel.com/docs/5.5/blade#control-structures



回答5:

You can simply check if the section exists:

if (isset($__env->getSections()['title'])) {      @yield('title'); } 

And you can even go a step further and pack this little piece of code into a Blade extension: http://laravel.com/docs/templates#extending-blade



回答6:

why not pass the title as a variable View::make('home')->with('title', 'Your Title') this will make your title available in $title



回答7:

I don't think you can, but you have options, like using a view composer to always provide a $title to your views:

View::composer('*', function($view) {     $title = Config::get('app.title');      $view->with('title', $title ? " - $title" : ''); }); 


回答8:

Can you not do:

layout.blade.php

Sitename.com @section("title") Default @show

And in subtemplate.blade.php:

@extends("layout")  @section("title") My new title @stop 


回答9:

The way to check is to not use the shortcut '@' but to use the long form: Section.

' . $title . ''; ?> 


回答10:

Building on Collin Jame's answer, if it is not obvious, I would recommend something like this:

   {{ Config::get('site.title') }}    @if (trim($__env->yieldContent('title')))     - @yield('title')   @endif 


回答11:

@if (View::hasSection('my_section'))      @endif 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!