Is there an Laravel Blade Statement Tag (instead of just printing)?

Asked

Viewed 601 times

1

I was wondering if there’s any way to create expressions with Blade’s tags Laravel. I mean, the same way we use {{ $valor }} to be able to print something, it would be possible to use the Blade syntax to declare something, instead of just printing?

For example, some Engines template lets you do something like this:

 {% $valor = 1 %}
 {{ $valor }}

You can do it in Laravel?

  • There is no way, but Blade does not restrict the use of php in your views. so if you use <?php $value = 1 ? > {{ $value }} will print 1

  • "There is no way" is a very general statement. Have as it has, because Blade offers mechanism for you to create your own syntax, besides having a small workaround for it.

  • What would be the use of this statement? There really is no way to pass this variable by reference?

2 answers

2


Can be created a Directive of the Blade:

Blade::directive("variable", function($expression){
      $expression = str_replace(';','=', $expression);
      return "<?php $$expression; ?>";
});

To use in the View:

@variable(num1;1)
@variable(num2;'abcde')
@variable(num3;new \DateTime())
@variable(num4;array(1,2,3,4,5,6))

works like this @variable, amid parentheses one string separated by point and comma (;) before the comma is variable name and then it’s the content/value.

Code generated in the PHP:

<?php $num1=1; ?>
<?php $num2='abcde'; ?>
<?php $num3=new \DateTime(); ?>
<?php $num4=array(1,2,3,4,5,6); ?>

Reference:

Extending Blade

1

As already stated in some of the comments, Blade does not prevent the user from using php tags.

However, there are those who still prefer a solution in the Blade - like me.

Way 1 - The gambiarra

So the first option is to do a little gambiarra.

The Blade compilation {{ $valor }} for <?php echo $valor; ?> - I’ve already opened the source code and I know it’s like this.

The solution would be to do this:

{{ ''; $valor = 1 }}

That would be compiled for this:

 <?php echo ''; $valor = 1; ?>

It would still be possible to use the same gambiarra with the comments tag from Blade.

{{-- */ $valor = 1; /* --}}

The exit would be:

Way 2 - Extend Blade

I prefer this second form, because a gambiarra always generates confusion and problems, in the future.

We can extend the Blade and add a new syntax to your compiler. This is done through the method Blade::extend(Closure $closure).

For example, let’s define that expression {? $valor = 1 ?} be interpreted by Blade as <?php $valor = 1; ?>.

Just add the following statement to the file app/start/global.php:

Blade::extend(function($value) {
    return preg_replace('/\{\?(.+)\?\}/', '<?php ${1} ?>', $value);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.