Is it possible to create own blade method/tag or what is the solution to this?
For example in a blade file, it will contain multiple form-block
block like this:
<section class="container-fluid container-fixed-lg form-block">
<div class="row b-b b-grey">
<div class="col-xs-12 col-md-3 m-r-35">
<h2>Title</h2>
<p>Some content here</p>
</div>
<div class="col-xs-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
// Custom Block Here
</div>
</div>
</div>
</div>
</section>
Is there a way to improve the readability/maintainability to have something like this in a blade file:
@form-block('Title','Some content here')
// Custom Block Here
@end-form-block
Custom blade directives, as they are called, are a bit dirty to write, because you have to return a string that contains the HTML, plus maybe PHP code that will be run. What makes is even more dirty is that you do not get the parameters separately, you just get one string like "('Title', 'Some content')"
as input for your directives. A trick I just found out is that you could use array syntax to separate the parameters.
Blade::directive('formblock', function ($expression) {
return '
<section class="container-fluid container-fixed-lg form-block">
<div class="row b-b b-grey">
<div class="col-xs-12 col-md-3 m-r-35">
<h2><?=array' . $expression . '[0];?></h2>
<p><?=array' . $expression . '[1];?></p>
</div>
<div class="col-xs-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
';
});
Blade::directive('endformblock', function () {
return '
</div>
</div>
</div>
</div>
</section>
';
});
As I said, it's dirty, but this will work. Note that you cannot use dashes in your directive names, that is why I called them formblock
and endformblock
instead of form-block
and end-form-block
.
An easier approach is to just use the @include
directive to include partials. However, the code you have to write in your blade files is a bit more verbose:
@include('partials.form_block_start', ['title' => 'My Title', 'content' => 'The extra content..']);
Main content...
@include('partials.form_block_end');
Then create the two files in views/partials/form_block_start.blade.php
and views/partials/form_block_end.blade.php
. In the first one, you can use just the title and content as the variables $title
and $content
. See https://laravel.com/docs/5.2/blade#control-structures for more information.
You can write your own custom directives in blade to do whatever you want.
Your example looks like you're trying to generate forms. This is a package that might help. It is the form/html generator that was removed in Laravel 5 and is now supported by the community.