Question

i have started working in Laravel, and working with .blade.php templates, but am not able to understand the benefit for using blad.php and also while having a master page, why we put our code in some other pages with @sections and @yeild like

masterpage.blade.php

<div>
 @yeild(section)
</div>

index.balde.php

@section
 Hellow world
@endsection

why i need to do it like that? why we can't just put our Text in the same page instead of doing this method, what are the benefits if we code like that.

Was it helpful?

Solution

There are lot of benefits in using Blade with Laravel, please read it here http://culttt.com/2013/09/02/using-blade-laravel-4/

OTHER TIPS

The short answer for you questions is we do not need Blade engine in any project. However, using it brings many benefits.

Simplify script file

Like other templating engine, Blade engine simplify your PHP scripts by some replacement such as :

  • <?php echo $foo ?> changed to {{ $foo }} (reduce 8 characters)
  • <?php if ($condition): ?> changed to @if ($condition) (reduce 6 characters)
  • <?php echo trans('lang.key') ?> changed to @lang('lang.key') (reduce 11 characters)
  • ...

Try to calculate how many character you can save if using Blade engine in your script.

Another thing I love in Blade engine is that we can create our own custom control structure. If you are tired of typing $var->format('Y-m-d H:i:s') every time you need to output a DateTime object. You can create custom matcher with Blade

Blade::extend(function($view, $compiler)
{
    $pattern = $compiler->createMatcher('datetime');

    return preg_replace($pattern, '$1<?php echo $2->format('m/d/Y H:i'); ?>', $view);
});

Now, all you need to to is replace $var->format('Y-m-d H:i:s') by @datetime($var).

View inheritant

By supporting section, Blade engine help developer organize their view file in a hierarchical and logical way. Imagine that you have HTML code for some pages of your website: a home page, a category archive page and a single post page. All there page have the same header, footer and sidebar. If we " put our Text in the same page instead of doing this method", the content of there files have a large amount of similarities, which cause any changes in the future very painful.

With Blade sections, create a simple master layout file like that

<html>
    <body>
        @section('sidebar')
            <!-- this is header code -->
        @show
        @section('sidebar')
            <!-- this is sidebar code -->
        @show

        <div class="container">
            @yield('content')
        </div>

        @section('footer')
            <!-- this is footer code -->
        @show
    </body>
</html>

In the view file for each page, you only need to take care of the main content of the page, instead of other parts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top