-
Notifications
You must be signed in to change notification settings - Fork 69
How to choose a partial as a widget ?
As a rule of thumb when you see a section on your page which needs it's own SQL query and data manipulation apart from others. It is maybe a good candidate to be extracted into a widget class.
Remember SQL query and data manipulation
You may ask why we even need data manipulation ???
I bet you have encountered situations in which you need some logic in your templates to figure out what to print out.
for example you need to dynamically put a css class for sold out items based on a boolean value of your model.
you often write:
<div class="@if($product->instock) active @else inactive @endif>That can quickly make your template files muddy if not careful. but we can pre-compute the css class in our widget class and extract the if/else out of our template files like this:
in out widget class:
$product->_state = 'inactive'
if($product->instock){
$product->_state = 'active'
}Then in our template we just write:
<div class="{{ $product->_state }}">Tip: we conventionally prefix the state with an underscore to indicate that it is a computed property and is not coming from the database directly.