Is there any declaration declaration tag in Laravel Blade (instead of just printing)?

1

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

For example, some template engines allow you to do something like this:

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

Can you do this in Laravel ?

    
asked by anonymous 26.02.2016 / 12:14

2 answers

1

As already mentioned in some of the comments, the blade is not for the user to use php tags.

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

Way 1 - The gambiarra

So the first option is to do a little gambiarra.

The Blade compiles {{ $valor }} to <?php echo $valor; ?> - I have already opened the source code and I know it is so.

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 of Blade .

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

The output would be:

   

Way 2 - Extending the Blade

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

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

For example, let's say that the expression {? $valor = 1 ?} is interpreted by Blade as <?php $valor = 1; ?> .

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

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

A Blade directive can be created:

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

To use in View :

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

is the variable name and then it is the content / value .

Code generated in PHP :

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

Reference:

Extending Blade

    
14.09.2016 / 17:48