Laravel 5 在视图中访问自定义函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28381443/
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
Laravel 5 accessing custom functions in a view
提问by RavensGate
I would like to make it possible to add custom functions that I can use within a view. For instance I want to make it possible to call a function that will display data. I do not want to do this from the controller as I'm trying to make this as customisable as possible.
我想让添加可以在视图中使用的自定义函数成为可能。例如,我想让调用一个显示数据的函数成为可能。我不想从控制器执行此操作,因为我试图使其尽可能可定制。
Apparently someone sent me information on possible creating a service provider and injecting this into the base of the app?
显然有人向我发送了有关可能创建服务提供商并将其注入应用程序基础的信息?
回答by Nicolas Beauvais
You can create a custom helper function directly in bootstrap/app.php
but there are better ways.
您可以直接在bootstrap/app.php
其中创建自定义辅助函数,但有更好的方法。
If you just want simple functions like Laravel's helpers, create a helpers.php
file in your app directory and require it in your bootstrap/app.php
file, then you can create all the custom function you want in it, for example:
如果你只是想要像Laravel 的 helpers这样的简单函数,helpers.php
在你的 app 目录中创建一个文件并在你的文件中 require 它bootstrap/app.php
,那么你可以在其中创建你想要的所有自定义函数,例如:
<?php
function coolText($text) {
return 'Cool ' . $text;
}
and call it in your view:
并在您看来调用它:
<div>{{ coolText($someVar) }}</div>
For something more advanced you can create a Helper class in your app directory, bind it in your AppServiceProvider.php
and add any method of your choice in this class.
对于更高级的东西,您可以在您的应用程序目录中创建一个 Helper 类,将其绑定到您的AppServiceProvider.php
并在此类中添加您选择的任何方法。
app/Helpers.php
应用程序/Helpers.php
<?php namespace Helpers;
class Helpers
{
public function coolText($text)
{
return 'Cool ' . $text;
}
}
You can inject this class in your view or create a Facadefor this class to access it in your view:
你可以在你的视图中注入这个类或者为这个类创建一个Facade来在你的视图中访问它:
<div>{{ Helpers::coolText($someVar) }}</div>