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

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

问题描述

我正在阅读Laravel刀片文档,但我不知道如何分配模板中的变量供以后使用.我无法执行{{ $old_section = "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天全站免登陆