Reputation: 10422
In working with laravel blade templates, what's the approved way to manage variables in output?
For example, I'm working on a view that shows upcoming chores / tasks for each farmer. The pivot table holds a due_at
datetime field for the task, and I'd like to change the class of the item depending on whether it's overdue, done, etc.
@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
This example throws an error: Undefined variable: style (View: /home/vagrant/Code/app/views/farmers/show.blade.php)
I don't see an obvious way to do simple code blocks to set variables like I'd do in a "normal" PHP view to define the class to apply to the task item by doing some basic calculations on the due_at
value.
Should this logic be moved to a helper function or something?
Upvotes: 2
Views: 2738
Reputation:
@Anam Your answer works, but I will use following method.
@user101289 Assuming that you have default layout and it yields content section. So to declare and use variables I would suggest you use vars
section in your inner template file and declare all your variables all at once on the top. And then use it. Since we will not yield the section vars
, it will not going to print it.
This will help you to keep track of variables used and its standard method to declare all variables on top and use in rest of the program:
@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
Upvotes: 0
Reputation: 12199
Assume due_at
is a timestamp.
@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
Upvotes: 2