php 如何在 Laravel Blade 模板中设置变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13002626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:38:42  来源:igfitidea点击:

How to Set Variables in a Laravel Blade Template

phplaravellaravel-4laravel-blade

提问by duality_

I'm reading the Laravel Blade documentationand I can't figure out how to assign variables inside a template for use later. I can't do {{ $old_section = "whatever" }}because that will echo "whatever" and I don't want that.

我正在阅读 Laravel Blade文档,但不知道如何在模板中分配变量以供以后使用。我不能这样做,{{ $old_section = "whatever" }}因为那会回响“随便”,我不想要那样。

I understand that I can do <?php $old_section = "whatever"; ?>, but that's not elegant.

我知道我可以做到<?php $old_section = "whatever"; ?>,但这并不优雅。

Is there a better, elegant way to do that in a Blade template?

在 Blade 模板中有没有更好、更优雅的方法来做到这一点?

采纳答案by TLGreg

It is discouraged to do in a view so there is no blade tag for it. If you do want to do this in your blade view, you can either just open a php tag as you wrote it or register a new blade tag. Just an example:

不鼓励在视图中执行,因此没有刀片标签。如果您确实想在刀片视图中执行此操作,您可以在编写时打开一个 php 标签或注册一个新的刀片标签。只是一个例子:

<?php
/**
 * <code>
 * {? $old_section = "whatever" ?}
 * </code>
 */
Blade::extend(function($value) {
    return preg_replace('/\{\?(.+)\?\}/', '<?php  ?>', $value);
});

回答by Pim

LARAVEL 5.5 AND UP

Laravel 5.5 及更高版本

The @php blade directive no longer accepts inline tags. Instead, use the full form of the directive:

@php 刀片指令不再接受内联标签。相反,使用指令的完整形式:

@php
$i = 1
@endphp

LARAVEL 5.2 AND UP

Laravel 5.2 及更高版本

You can just use:

你可以只使用:

@php ($i = 1)

Or you can use it in a block statement:

或者您可以在块语句中使用它:

@php
$i = 1
@endphp

LARAVEL 5

拉拉维尔 5

Extend Blade like this:

像这样扩展刀片:

/*
|--------------------------------------------------------------------------
| Extend blade so we can define a variable
| <code>
| @define $variable = "whatever"
| </code>
|--------------------------------------------------------------------------
*/

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

Then do one of the following:

然后执行以下操作之一:

Quick solution: If you are lazy, just put the code in the boot() function of the AppServiceProvider.php.

快速解决方案:如果你偷懒,把代码放在 AppServiceProvider.php 的 boot() 函数中。

Nicer solution: Create an own service provider. See https://stackoverflow.com/a/28641054/2169147on how to extend blade in Laravel 5. It's a bit more work this way, but a good exercise on how to use Providers :)

更好的解决方案:创建一个自己的服务提供者。有关如何在 Laravel 5 中扩展刀片的信息,请参阅https://stackoverflow.com/a/28641054/2169147。这种方式需要做更多的工作,但这是关于如何使用 Providers 的一个很好的练习:)

LARAVEL 4

拉维尔 4

You can just put the above code on the bottom of app/start/global.php(or any other place if you feel that is better).

你可以把上面的代码放在app/start/global.php的底部(或者任何其他你觉得更好的地方)。



After the above changes, you can use:

进行上述更改后,您可以使用:

@define $i = 1

to define a variable.

定义一个变量。

回答by Trying Tobemyself

In laravel-4, you can use the template comment syntax to define/set variables.

laravel-4 中,您可以使用模板注释语法来定义/设置变量。

Comment syntax is {{-- anything here is comment --}}and it is rendered by bladeengine as

注释语法是 {{-- anything here is comment --}},它由刀片引擎呈现为

<?php /* anything here is comment */ ?>

<?php /* anything here is comment */ ?>

so with little trick we can use it to define variables, for example

因此,我们可以使用它来定义变量,例如

{{-- */$i=0;/* --}}

will be rendered by bladeas <?php /* */$i=0;/* */ ?>which sets the variable for us. Without changing any line of code.

将呈现叶片<?php /* */$i=0;/* */ ?>它设置的变量我们。无需更改任何代码行。

回答by BTMPL

There is a simple workaround that doesn't require you to change any code, and it works in Laravel 4 just as well.

有一个简单的解决方法,不需要您更改任何代码,它也适用于 Laravel 4。

You just use an assignment operator (=) in the expression passed to an @ifstatement, instead of (for instance) an operator such as ==.

您只需=在传递给@if语句的表达式中使用赋值运算符 ( ) ,而不是(例如)诸如==.

@if ($variable = 'any data, be it string, variable or OOP') @endif

Then you can use it anywhere you can use any other variable

然后你可以在任何可以使用任何其他变量的地方使用它

{{ $variable }}

The only downside is your assignment will looklike a mistake to someone not aware that you're doing this as a workaround.

唯一的缺点是,对于不知道您正在这样做的人来说,您的任务看起来像是一个错误的解决方法。

回答by Sabrina Leggett

Ya'll are making it too complicated.

你们会让它变得太复杂。

Just use plain php

只需使用普通的 php

<?php $i = 1; ?>
{{$i}}

donesies.

甜甜圈。

(or https://github.com/alexdover/blade-setlooks pretty straighforward too)

(或者https://github.com/alexdover/blade-set看起来也很简单)

We're all kinda "hacking" the system by setting variables in views, so why make the "hack" more complicated then it needs to be?

我们都通过在视图中设置变量来“入侵”系统,那么为什么要让“黑客”变得更复杂呢?

Tested in Laravel 4.

在 Laravel 4 中测试。

Another benefit is that syntax highlighting works properly (I was using comment hack before and it was awful to read)

另一个好处是语法高亮可以正常工作(我之前使用过注释 hack,读起来很糟糕)

回答by Prince Ahmed

You Can Set Variables In The Blade Templating Engine The Following Ways:

1. General PHP Block
Setting Variable:<?php $hello = "Hello World!"; ?>
Output:{{$hello}}

2. Blade PHP Block
Setting Variable:@php $hello = "Hello World!"; @endphp
Output:{{$hello}}

您可以在 Blade 模板引擎中设置变量,方法如下:

1. 通用 PHP 块
设置变量:<?php $hello = "Hello World!"; ?>
输出:{{$hello}}

2. 刀片 PHP 块
设置变量:@php $hello = "Hello World!"; @endphp
输出:{{$hello}}

回答by Daan

Since Laravel 5.2.23, you have the @php Blade directive, which you can use inline or as block statement:

从 Laravel 5.2.23 开始,你有了@php Blade 指令,你可以使用内联或块语句:

@php($old_section = "whatever")

or

或者

@php
    $old_section = "whatever"
@endphp

回答by Vasile Goian

You can set a variable in the view file, but it will be printed just as you set it. Anyway, there is a workaround. You can set the variable inside an unused section. Example:

您可以在视图文件中设置一个变量,但它会按照您设置的方式打印出来。无论如何,有一个解决方法。您可以在未使用的部分中设置变量。例子:

@section('someSection')
  {{ $yourVar = 'Your value' }}
@endsection

Then {{ $yourVar }}will print Your valueanywhere you want it to, but you don't get the output when you save the variable.

然后{{ $yourVar }}Your value在您想要的任何地方打印,但在保存变量时不会得到输出。

EDIT:naming the section is required otherwise an exception will be thrown.

编辑:命名该部分是必需的,否则将引发异常。

回答by Justin

In Laravel 4:

在 Laravel 4 中:

If you wanted the variable accessible in all your views, not just your template, View::shareis a great method (more info on this blog).

如果您希望在您的所有视图中访问该变量,而不仅仅是您的模板,这View::share是一个很好的方法(有关此博客的更多信息)。

Just add the following in app/controllers/BaseController.php

只需在app/controllers/BaseController.php 中添加以下内容

class BaseController extends Controller
{
  public function __construct()
  {                   
    // Share a var with all views
    View::share('myvar', 'some value');
  }
}

and now $myvarwill be available to all your views -- including your template.

现在$myvar将可用于您的所有视图——包括您的模板。

I used this to set environment specific asset URLs for my images.

我用它来为我的图像设置特定于环境的资产 URL。

回答by Michael J. Calkins

And suddenly nothing will appear. From my experience, if you have to do something like this prepare the html in a model's method or do some reorganizing of your code in to arrays or something.

突然什么都不会出现。根据我的经验,如果您必须执行这样的操作,请在模型的方法中准备 html,或者将代码重新组织为数组或其他内容。

There is never just 1 way.

从来没有只有一种方式。

{{ $x = 1 ? '' : '' }}