duanliang1019 2016-10-12 06:25
浏览 90
已采纳

在Laravel的刀片模板功能中使用Handlebars数据

I want to use Handlebars data (i.e. {{ id }}) as a parameter in Laravel helper function on .blade template view.

I know about escaping Handlebars brackets when using .blade.php extension like @{{#each users}} or @{{ name }} and that works perfectly.

The problem comes when I want to use @{{ id}} within Laravel's helper function because of nested double curly brackets:

<a href="#" class="btn btn-xs btn-warning" data-route="{{ route('admin.membership.toggle-show-hide', ['id' => @{{ id }}]) }}">
    Hide
</a>

I know this can't work because helper function route doesn't expect curly bracket in parameters array but I still need to be able to pass data from Handlebars contex into Laravel's helper function on blade template view somehow.

I tried different ways to achieve this, but without success.

Does anyone knows some workaround or has any idea for this? Thank you all in advance.

EDIT

The alternative (which I currently use) is to write a Handlebars helper which will accept needed parameter and generate route for some action:

Handlebars.registerHelper("mmbrshpToggleShowHideRoute", function(id) {
    return APP_URL + '/admin/membership/' + id + '/toggleShowHide';
});

Using this, I can generate route string in Handlebars template (with .blade.php extension) for each item in Handlebars JSON context retrieved from Laravel's controller:

<a href="#" class="btn btn-xs btn-success" data-route="{{ mmbrshpToggleShowHideRoute id }}">
    Hide
</a>

I don't like this approach because I'm actually hardcoding the route URL in Handlebars helper function. This works and provides reusabillity throughout the views and templates, but it would be nicer if there was possibility to generate route using Laravel's route helper function and just pass an id parameter from Handlebars context.

  • 写回答

3条回答 默认 最新

  • douduan5086 2016-10-12 09:46
    关注

    If you really need "bulletproof" solution for changing routes on frontend than most convenient solution is to make an accessor for route in your model. Something like this:

    public function getRouteAttribute()
    {
        return route('admin.membership.toggle-show-hide', ['id' => $this->id]);
    }
    

    Then you need to make sure that accessor is always available (even if you return JSON response) in your object instances using $appends property like this:

    protected $appends = ['route'];
    

    That should be it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容