[英]How to call custom classes/methods from laravel blade view?
I have a view that renders some dates that I want to show in different ways based on the type of client that connects to my app.我有一个视图,可以根据连接到我的应用程序的客户端类型以不同的方式呈现一些我想显示的日期。 Initially the dates comes from a huge json that my controller gets from a webservice/API in this format
最初的日期来自一个巨大的 json,我的 controller 从这种格式的 web 服务/API 获得
YYYYMMDDHHMMSS
// 2022-03-15 18:30:00 is 20220315183000
what I did is to use a class/helper that I have wrote in my app folder, to manipulate how those dates looks我所做的是使用我在我的应用程序文件夹中编写的类/帮助程序来操纵这些日期的外观
CONTENT OF App/ConvertTimestamp.php应用内容/ConvertTimestamp.php
<?php
/**
* Helper timestamp
*/
namespace App;
class ConvertTimestamp {
private $timestamp;
// Style one date
public static function styleOne($timestamp) {
// Some manipulation here
/* CODE */
return $frontDate;
}
// Style two date
public static function styleTwo($timestamp) {
// Some manipulation here
/* CODE */
return $realDate;
}
}
what I want to do now is to call this class in my blade file, I tried different approaches, the first one was simply to open php tags inside the blade file to use the related namespace like this我现在要做的是在我的刀片文件中调用这个 class ,我尝试了不同的方法,第一种方法是简单地打开刀片文件中的 php 标记以使用像这样的相关命名空间
CONTENT OF resources/views/view.blade.php资源/视图/view.blade.php 的内容
<?php use App\ConvertTimestamp ?>
<h2>The style one date is: </h2>
<h3>{{ ConvertTimestamp::styleOne($timestamp) }}</h3>
<h2>The style two date is: </h2>
<h3>{{ ConvertTimestamp::styleTwo($timestamp) }}</h2>
or to directly prepend the path to the class name in this way(I'm currently using this kind of approache)或以这种方式直接添加到 class 名称的路径(我目前正在使用这种方法)
CONTENT OF resources/views/view.blade.php资源/视图/view.blade.php 的内容
<h2>The style one date is: </h2>
<h3>{{ \App\ConvertTimestamp::styleOne($timestamp) }}</h3>
<h2>The style two date is: </h2>
<h3>{{ \App\ConvertTimestamp::styleTwo($timestamp) }}</h2>
so the question is, there is a better way to import classes from the controller to that specific view or to all the views, something like this所以问题是,有一种更好的方法可以将类从 controller 导入到该特定视图或所有视图,如下所示
CONTENT OF controller controller的内容
public function index(){
$data = 'some data';
return view('home', $data)->useNamespace('App\ConvertTimestamp');
}
You can put all classes in the config Laravel folder app.php aliases您可以将所有类放在配置 Laravel 文件夹 app.php 别名中
'aliases' => [
"ConvertTimestamp" => App\ConvertTimestamp,
]
Now you can use all your static functions all over the blades and controllers too.现在,您也可以在刀片和控制器上使用所有 static 功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.