I can define a variable using below in blade
<?php $var = var1 - var2; ?>
and then print it as
{{ $var }}
but how to set a variable using laravel blade template method and then use it, basically @set alternative in 5.2?
There is this package for laravel 4 but it's not compatible with laravel5 due to it's composer file. A quick pull request would fix that.
The main part of the package is only three lines which could be added to your AppServiceProvider
's boot method if you didn't want to pull in a package for it:
\Blade::extend(function($value, $compiler) {
$value = preg_replace("/@set\('(.*?)'\,(.*)\)/", '<?php $$1 = $2; ?>', $value);
return $value;
});
Here's some examples from the readme.
@set('my_variable', $existing_variable)
You can then use the variable $my_variable
in the template.
You might choose to fetch a bunch of models from your template, for example
@set('my_model_list', MyModel::where('something', '=', 1)->paginate(10))
You can use blade comment syntax
{{--*/ $var = $var1 - $var2; /*--}}
{{ $var }}
Code above will be translated to following snippet
<?php /**/ $var = $var1 - $var2; /**/ ?>
Read more: http://laravel-recipes.com/recipes/256/assigning-a-variable-in-a-blade-template
Try this,
@if($var=$var1-$var2)@endif
and print,
{{ $var }}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.