Reputation: 422
I'm using Laravel
I want to make my code shorter and I decided to use for loop for many actions
I have feature_1
, feature_2
to feature_10
so I used this code :
@for ($i=1; $i <= 10; $i++)
<div class="wrapper">
@if ($product->feature_.$i)
<li class="ty-compact-list">{{ $product->feature_.$i }} </li>
@endif
@endfor
But it does not work well and just echo number 1 to 10
Upvotes: 1
Views: 1368
Reputation: 8242
This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.
Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$.
It is also possible to access class properties using variables within strings using this syntax.
<?php
class foo {
var $bar = 'I am bar.';
}
$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo "{$foo->$bar}\n";
echo "{$foo->{$baz[1]}}\n";
?>
So in your case it would be:
@for ($i=1; $i <= 10; $i++)
<div class="wrapper">
@if ($product->{"feature_{$i}"})
<li class="ty-compact-list">{{ $product->{"feature_{$i}"} }} </li>
@endif
@endfor
Upvotes: 1