如何在 laravel 4 中的blade.php tempate 中使用静态函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17051974/
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
How do I use a static function in blade.php tempate in laravel 4?
提问by Jason Spick
I have a class public static method that grabs some database information and returns a integer. In a controller i can call that method just fine. How do i call that static method in a blade template?
我有一个类公共静态方法,它获取一些数据库信息并返回一个整数。在控制器中,我可以很好地调用该方法。我如何在刀片模板中调用该静态方法?
For example:
例如:
@foreach ($tasks as $task)
{{Task::percentComplete($task->id)}}%<br />
@endforeach
Thank you
谢谢
回答by Alexandre Danault
You could either
你也可以
A- Make it a Facade : http://laravel.com/docs/facades
A- 让它成为外观:http: //laravel.com/docs/facades
B- Move it into a helper/library : https://stackoverflow.com/a/13481218/2446119
B- 将其移动到助手/库中:https: //stackoverflow.com/a/13481218/2446119
I personally think that helpers and libraries are much easier and quicker to code, but facades are cleaner.
我个人认为助手和库更容易和更快地编写代码,但外观更干净。
回答by angelcool.net
One hackish way to do it is just embedding PHP in your blade template, at least in Laravel 4.0; I migrated an old project, poorly written, to laravel. Being so overwhelmed by the number of issues I ran into and time constraints I did not have time to look for a better way to do it. I did a bunch of html forms totaling about 30k lines of code.
一种骇人听闻的方法是将 PHP 嵌入到您的刀片模板中,至少在 Laravel 4.0 中是这样;我将一个写得很糟糕的旧项目迁移到 Laravel。被我遇到的问题数量和时间限制所淹没,我没有时间寻找更好的方法来做到这一点。我做了一堆 html 表单,总共大约 30k 行代码。
<?php
$haystack=Session::get('orderInfo.form.conditions',array());
?>
Then you can access your data normally:
然后你就可以正常访问你的数据了:
{{in_array('Special Assignments',$haystack)?'checked="checked"':''}}
That's what worked for me.
这就是对我有用的东西。
NOTE: Just adding my 2 cents for the sake of documentation. There are better and cleaner ways to do it, as stated by the accepted answer.
注意:为了文档起见,只需添加我的 2 美分。正如接受的答案所述,有更好、更干净的方法来做到这一点。