如何为所有 blade laravel 创建一个全局变量
How to make a global variable for all blade laravel
善良的人们。
我的项目有问题。
在布局blade中,我需要从数据库中获取一些数据。但是我无法传递变量,因为布局 blade 没有路由。简直是高手blade.
有什么方法可以创建一个全局变量并全部使用它吗blade?
感谢宝贵的回复。
拥有全局函数或变量有不同的方法
在我看来,最简单的方法是:
创建一个帮助程序 php 文件来恢复全局函数和变量,这样你
在 composer.json 中加载此文件,您可以在任何地方调用它。
我在 App/Helpers 目录中创建了 Functions.php 以恢复我的全局变量和函数。
然后在 composer.json 中声明文件:
“自动加载”,如果没有“文件(数组)”,则在其中添加它并将路径设置为
你的文件。在我的示例中,它是“app/Helpers/Functions.php”.
"autoload": {
"psr-4": {
"App\": "app/",
"Database\Factories\": "database/factories/",
"Database\Seeders\": "database/seeders/"
},
"files": [
"app/Helpers/Functions.php"
]
},
最后,重新运行
php artisan serve
为了访问您 blade 中的变量,我不确定您是否可以这样做(我试过了,但它是 returns 未定义的变量)。
你可以做到:
// in your helper file
myFunc() {
$myVar = 'value';
return $myVar;
}
// in your blade
{{ myFunc() }}
或使用类:
// in your helper file
class myClass {
protected $myVar = 'value';
protected static $staticVar = 'value';
public myFunc() {
return $this->myVar;
}
public static staticFunc() {
return myClass::$staticVar;
}
}
// in your blade
{{ (new myClass())->myFunc() }}
// of static function
{{ myClass::staticFunc() }}
希望,它能帮助...
您可以使用 laravel 帮助程序来声明全局变量,您可以创建自己的自定义帮助程序函数。
你可以关注 laravel custom helpers and this one to custom create helpers
Create a new Service Provider as suggested in here
将您的新服务提供商添加到配置文件 (config/app.php)。
在您的新服务提供商的启动方法中使用:
查看::分享('something_cool','this is a cool shared variable');
现在您可以在所有视图中使用 $something_cool。
善良的人们。
我的项目有问题。
在布局blade中,我需要从数据库中获取一些数据。但是我无法传递变量,因为布局 blade 没有路由。简直是高手blade.
有什么方法可以创建一个全局变量并全部使用它吗blade?
感谢宝贵的回复。
拥有全局函数或变量有不同的方法 在我看来,最简单的方法是:
创建一个帮助程序 php 文件来恢复全局函数和变量,这样你 在 composer.json 中加载此文件,您可以在任何地方调用它。
我在 App/Helpers 目录中创建了 Functions.php 以恢复我的全局变量和函数。
然后在 composer.json 中声明文件: “自动加载”,如果没有“文件(数组)”,则在其中添加它并将路径设置为 你的文件。在我的示例中,它是“app/Helpers/Functions.php”.
"autoload": {
"psr-4": {
"App\": "app/",
"Database\Factories\": "database/factories/",
"Database\Seeders\": "database/seeders/"
},
"files": [
"app/Helpers/Functions.php"
]
},
最后,重新运行
php artisan serve
为了访问您 blade 中的变量,我不确定您是否可以这样做(我试过了,但它是 returns 未定义的变量)。
你可以做到:
// in your helper file
myFunc() {
$myVar = 'value';
return $myVar;
}
// in your blade
{{ myFunc() }}
或使用类:
// in your helper file
class myClass {
protected $myVar = 'value';
protected static $staticVar = 'value';
public myFunc() {
return $this->myVar;
}
public static staticFunc() {
return myClass::$staticVar;
}
}
// in your blade
{{ (new myClass())->myFunc() }}
// of static function
{{ myClass::staticFunc() }}
希望,它能帮助...
您可以使用 laravel 帮助程序来声明全局变量,您可以创建自己的自定义帮助程序函数。 你可以关注 laravel custom helpers and this one to custom create helpers
Create a new Service Provider as suggested in here
将您的新服务提供商添加到配置文件 (config/app.php)。
在您的新服务提供商的启动方法中使用:
查看::分享('something_cool','this is a cool shared variable'); 现在您可以在所有视图中使用 $something_cool。