【问题标题】:How to get View data in Laravel in custom helper or directive如何在自定义助手或指令中获取 Laravel 中的视图数据
【发布时间】:2019-08-16 16:42:26
【问题描述】:

我需要在自定义帮助器或指令中获取从控制器传递的所有视图数据,这在此视图刀片模板中被调用。

所以在刀片模板中有翻译:

@lang($periodName . '.H1 title', ['time' => $time])

我想让它更短。为此,我创建了助手 periodTrans('H1 Title')。

function periodTrans($title) {
 return __($periodName . '.' . $title,  ['time' => $time]);
}

有没有办法让辅助函数内部访问 $periodName$time 变量,而不是像参数一样传递它们并使函数更短?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    AFAIK 这应该可以工作。

    在你的controller:

    public function __construct()
    {
        .....
        \View::share('periodName', $periodName);
        \View::share('time', $time);
    }
    
    

    你的助手:

    function periodTrans($title) {
        $data = \View::getShared(); 
        return __($data['periodName'] . '.' . $title,  ['time' => $data['time']]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多