繁体   English   中英

laravel刀片模板变量

[英]laravel blade template variables

在使用laravel刀片模板时,已批准的管理输出变量的方法是什么?

例如,我正在处理一个视图,该视图显示每个农民即将要做的家务/任务。 数据透视表包含任务的due_at datetime字段,我想根据项目的过期,完成等来更改项目的类。

@foreach ($farmer->tasks as $task)
    @if ($task->pivot->due_at) < date(now))
        $style = 'alert alert-danger';
    @elseif ($task->pivot->due_at) > date(now))
        $style = 'alert alert-success';
    @else
        $style = '';
    @endif
    <div class="list-group-item {{ $style }}">{{$task->name}} <span class="glyphicon glyphicon-calendar"> {{ $task->pivot->due_at }}</span> <span class="glyphicon glyphicon-pencil"></span><span class="glyphicon glyphicon-trash"></span></div>
@endforeach 

此示例引发错误: Undefined variable: style (View: /home/vagrant/Code/app/views/farmers/show.blade.php)

我没有看到一种简单的代码块来设置变量的明显方法,就像我在“正常” PHP视图中那样通过对due_at值进行一些基本计算来定义要应用于任务项的类due_at

是否应将此逻辑移至辅助功能或其他功能?

假设due_at是一个时间戳。

@foreach ($farmer->tasks as $task)
    @if (Carbon::parse($task->pivot->due_at) < Carbon::now())
        <?php $style = 'alert alert-danger'; ?>
    @elseif (Carbon::parse($task->pivot->due_at) > Carbon::now())
        <?php $style = 'alert alert-success'; ?>
    @else
        <?php $style = ''; ?>
    @endif
    <div class="list-group-item {{ $style }}">{{$task->name}} <span class="glyphicon glyphicon-calendar"> {{ $task->pivot->due_at }}</span> <span class="glyphicon glyphicon-pencil"></span><span class="glyphicon glyphicon-trash"></span></div>
@endforeach 

@Anam您的答案有效,但是我将使用以下方法。

@ user101289假定您具有默认布局,并且将产生内容部分。 因此,要声明和使用变量,我建议您在内部模板文件中使用vars部分,并一次在顶部声明所有变量。 然后使用它。 由于我们不会产生vars节,因此不会打印它。

这将帮助您跟踪使用的变量及其标准方法,以在所有程序顶部声明所有变量并在程序的其余部分中使用:

@extends('layouts.default') /* Your default layout template file. */
@section("vars")
  {{ $yourVar = 'Your value' }}
@endsection
@section("content") /* The content section which we will print */
    // Your other HTML and FORM code and you can use variables defined in **vars** section
@endsection
@stop

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM