简体   繁体   English

Laravel 5.2:如何在没有php标签的刀片模板中设置变量?

[英]Laravel 5.2 : how to set a variable in blade template, without php tags?

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? 但是如何使用laravel刀片模板方法设置变量然后使用它,基本上是5.2中的@set替代方法?

There is this package for laravel 4 but it's not compatible with laravel5 due to it's composer file. laravel 4有此软件包,但由于其composer文件而与laravel5不兼容。 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: 软件包的主要部分只有三行,如果您不想为其引入软件包,则可以将其添加到AppServiceProvider的启动方法中:

\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. 然后,您可以在模板中使用变量$my_variable


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 了解更多: http : //laravel-recipes.com/recipes/256/assigning-a-variable-in-a-blade-template

Try this, 尝试这个,

@if($var=$var1-$var2)@endif

and print, 然后打印

{{ $var }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM