如何在 Laravel Blade 模板中设置变量 [英] How to Set Variables in a Laravel Blade Template

查看:38
本文介绍了如何在 Laravel Blade 模板中设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm reading the Laravel Blade documentation and 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.

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

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

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

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

推荐答案

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

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
/**
 * <code>
 * {? $old_section = "whatever" ?}
 * </code>
 */
Blade::extend(function($value) {
    return preg_replace('/{?(.+)?}/', '<?php ${1} ?>', $value);
});

这篇关于如何在 Laravel Blade 模板中设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆