Skip to content

Commit

Permalink
Add Blade::component method for component aliases
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastiandedeyne committed Jan 15, 2018
1 parent b52d314 commit 4ab37bb
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/Illuminate/View/Compilers/BladeCompiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,30 @@ public function check($name, ...$parameters)
return call_user_func($this->conditions[$name], ...$parameters);
}

/**
* Register a component alias.
*
* @param string $path
* @param string $alias
* @return void
*/
public function component($path, $alias = null)
{
$alias = $alias ?: array_last(explode('.', $path));

$this->directive($alias, function ($expression) use ($path) {
if ($expression) {
return "<?php \$__env->startComponent('{$path}', {$expression}); ?>";
} else {
return "<?php \$__env->startComponent('{$path}'); ?>";
}
});

$this->directive('end'.$alias, function ($expression) use ($path) {
return '<?php echo $__env->renderComponent(); ?>';
});
}

/**
* Register a handler for custom directives.
*
Expand Down
33 changes: 33 additions & 0 deletions tests/View/Blade/BladeCustomTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,37 @@ public function testCustomIfElseConditions()
<?php endif; ?>';
$this->assertEquals($expected, $this->compiler->compileString($string));
}

public function testCustomComponents()
{
$this->compiler->component('app.components.alert', 'alert');

$string = '@alert
@endalert';
$expected = '<?php $__env->startComponent(\'app.components.alert\'); ?>
<?php echo $__env->renderComponent(); ?>';
$this->assertEquals($expected, $this->compiler->compileString($string));
}

public function testCustomComponentsWithSlots()
{
$this->compiler->component('app.components.alert', 'alert');

$string = '@alert([\'type\' => \'danger\'])
@endalert';
$expected = '<?php $__env->startComponent(\'app.components.alert\', [\'type\' => \'danger\']); ?>
<?php echo $__env->renderComponent(); ?>';
$this->assertEquals($expected, $this->compiler->compileString($string));
}

public function testCustomComponentsDefaultAlias()
{
$this->compiler->component('app.components.alert');

$string = '@alert
@endalert';
$expected = '<?php $__env->startComponent(\'app.components.alert\'); ?>
<?php echo $__env->renderComponent(); ?>';
$this->assertEquals($expected, $this->compiler->compileString($string));
}
}

0 comments on commit 4ab37bb

Please sign in to comment.