diff --git a/src/Illuminate/View/Compilers/BladeCompiler.php b/src/Illuminate/View/Compilers/BladeCompiler.php index 1634602b0b64..e188990f1aab 100644 --- a/src/Illuminate/View/Compilers/BladeCompiler.php +++ b/src/Illuminate/View/Compilers/BladeCompiler.php @@ -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 "startComponent('{$path}', {$expression}); ?>"; + } else { + return "startComponent('{$path}'); ?>"; + } + }); + + $this->directive('end'.$alias, function ($expression) use ($path) { + return 'renderComponent(); ?>'; + }); + } + /** * Register a handler for custom directives. * diff --git a/tests/View/Blade/BladeCustomTest.php b/tests/View/Blade/BladeCustomTest.php index 368fc793ecad..2c9a8e54c2d1 100644 --- a/tests/View/Blade/BladeCustomTest.php +++ b/tests/View/Blade/BladeCustomTest.php @@ -90,4 +90,37 @@ public function testCustomIfElseConditions() '; $this->assertEquals($expected, $this->compiler->compileString($string)); } + + public function testCustomComponents() + { + $this->compiler->component('app.components.alert', 'alert'); + + $string = '@alert +@endalert'; + $expected = 'startComponent(\'app.components.alert\'); ?> +renderComponent(); ?>'; + $this->assertEquals($expected, $this->compiler->compileString($string)); + } + + public function testCustomComponentsWithSlots() + { + $this->compiler->component('app.components.alert', 'alert'); + + $string = '@alert([\'type\' => \'danger\']) +@endalert'; + $expected = 'startComponent(\'app.components.alert\', [\'type\' => \'danger\']); ?> +renderComponent(); ?>'; + $this->assertEquals($expected, $this->compiler->compileString($string)); + } + + public function testCustomComponentsDefaultAlias() + { + $this->compiler->component('app.components.alert'); + + $string = '@alert +@endalert'; + $expected = 'startComponent(\'app.components.alert\'); ?> +renderComponent(); ?>'; + $this->assertEquals($expected, $this->compiler->compileString($string)); + } }