Blade @render without inherited scope

Submitted by fedeisas - 10 years ago

Sometimes you want to render a partial without sharing all the scope. I often found that the scope inheritance between highly decoupled UI modules makes hard to find errors, because we end up using similar variable names in each module (using @include) Let me show you an example:

<?php

// start/global.php
Blade::extend(function ($view) {
    $pattern = Blade::createOpenMatcher('render');
    $replace = '$1<?php echo $__env->make$2)->render(); ?>';
    return preg_replace($pattern, $replace, $view);
});

// views/hello.blade.php
<?php $title = 'My Title'; ?>
{{ $title }} // Echo My Title
@render('user', ['name' => 'John'])

// views/title.user.php
{{ $name }} // Echo John
{{ $title or 'Jane' }} // Echo Jane because $title is not defined