Skip to content

Commit

Permalink
[5.x] Adds "no_results" to automatic array variables (#11234)
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnathonKoster authored Dec 11, 2024
1 parent 6adc8d4 commit b51b692
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/View/Antlers/Language/Runtime/NodeProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -2550,6 +2550,7 @@ protected function addLoopIterationVariables($loop)
$value['count'] = $index + 1;
$value['index'] = $index;
$value['total_results'] = $total;
$value['no_results'] = false;
$value['first'] = $index === 0;
$value['last'] = $index === $lastIndex;

Expand Down
73 changes: 73 additions & 0 deletions tests/Antlers/Runtime/TemplateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Str;
use Illuminate\Support\ViewErrorBag;
use Mockery;
use PHPUnit\Framework\Attributes\DataProvider;
Expand All @@ -22,6 +23,7 @@
use Statamic\Fields\LabeledValue;
use Statamic\Fields\Value;
use Statamic\Fields\Values;
use Statamic\Tags\Concerns\OutputsItems;
use Statamic\Tags\Tags;
use Statamic\View\Cascade;
use Tests\Antlers\Fixtures\Addon\Tags\RecursiveChildren;
Expand Down Expand Up @@ -2599,6 +2601,77 @@ public function test_it_returns_escaped_content()
$input = 'Hey, look at that @{{ noun }}!';
$this->assertSame('Hey, look at that {{ noun }}!', $this->renderString($input, []));
}

#[Test]
public function no_results_value_is_added_automatically()
{
(new class extends Tags
{
use OutputsItems;
public static $handle = 'the_tag';

public function index()
{
if ($this->params->get('has_value')) {
return $this->output(collect([
'one',
'two',
'three',
]));
}

return $this->parseNoResults();
}
})::register();

$template = <<<'TEMPLATE'
{{ the_tag }}
{{ if no_results }}
No Results 1.
{{ the_tag has_value="true" }}
{{ if no_results }}
No Results 2.
{{ else }}
{{ value }}
{{ /if }}
{{ /the_tag }}
{{ if no_results }} No Results 1.1 {{ /if }}
{{ else }}
Has Results 1.
{{ /if }}
{{ /the_tag }}
TEMPLATE;

$this->assertSame(
'No Results 1. one two three No Results 1.1',
Str::squish($this->renderString($template, [], true))
);

$template = <<<'TEMPLATE'
{{ the_tag }}
{{ if no_results }}
No Results 1.
{{ the_tag has_value="true" as="items" }}
{{ if no_results }}
No Results 2.
{{ else }}
{{ items }}{{ value }} {{ /items }}
{{ /if }}
{{ /the_tag }}
{{ if no_results }} No Results 1.1 {{ /if }}
{{ else }}
Has Results 1.
{{ /if }}
{{ /the_tag }}
TEMPLATE;

$this->assertSame(
'No Results 1. one two three No Results 1.1',
Str::squish($this->renderString($template, [], true))
);
}
}

class NonArrayableObject
Expand Down

0 comments on commit b51b692

Please sign in to comment.