【问题标题】:How to pass a custom function to a Laravel Blade template?如何将自定义函数传递给 Laravel Blade 模板?
【发布时间】:2015-12-02 12:18:28
【问题描述】:

我有一个自定义函数,我想在刀片模板中传递它。这是函数:

function trim_characters( $text, $length = 45, $append = '…' ) {

    $length = (int) $length;
    $text = trim( strip_tags( $text ) );

    if ( strlen( $text ) > $length ) {
        $text = substr( $text, 0, $length + 1 );
        $words = preg_split( "/[\s]| /", $text, -1, PREG_SPLIT_NO_EMPTY );
        preg_match( "/[\s]| /", $text, $lastchar, 0, $length );
        if ( empty( $lastchar ) )
            array_pop( $words );

        $text = implode( ' ', $words ) . $append;
    }

    return $text;
}

而且用法是这样的:

$string = "A VERY VERY LONG TEXT";
trim_characters( $string );

是否可以将自定义函数传递给刀片模板?谢谢。

【问题讨论】:

    标签: laravel laravel-blade


    【解决方案1】:

    你不必传递任何东西给刀片。如果你定义了你的函数,你可以从刀片中使用它。


    1. 创建一个新的app/helpers.php 文件。
    2. 将您的trim_characters 函数添加到其中。
    3. Add that file to your composer.json file
    4. 运行composer dump-autoload

    现在直接在blade中使用函数:

    {{ trim_characters($string) }}
    

    【讨论】:

    • 对我不起作用。我得到Call to undefined function,该函数以纯文本形式打印在页面顶部!?
    • 非常适合我。谢谢。
    • @Joseph Silber 有没有办法使用 laravel 5.3 使用 web.php 在主机上运行“composer dump-autoload”命令
    【解决方案2】:

    另一种方法是注入服务。请参阅https://laravel.com/docs/6.x/blade#service-injection 的文档

    在一个类中定义你的函数,然后将它注入你的 Blade

    class Foo {
        trim_characters($string) {....}
    }
    

    然后在你的刀片文件中

    @inject('foo', 'Foo')
    
    <div>{{ $foo->trim_characters($string) }}</div>
    

    【讨论】:

      猜你喜欢
      • 2014-07-17
      • 2016-02-05
      • 2012-08-17
      • 2014-07-17
      • 2012-11-24
      • 2011-11-10
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      相关资源
      最近更新 更多