[英]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.