Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add when and unless to partial tag #7054

Merged
merged 3 commits into from Nov 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/Tags/Partial.php
Expand Up @@ -15,6 +15,10 @@ public function wildcard($tag)

protected function render($partial)
{
if (! $this->shouldRender()) {
return;
}

$variables = array_merge($this->context->all(), $this->params->all(), [
'__frontmatter' => $this->params->all(),
'slot' => $this->isPair ? trim($this->parse()) : null,
Expand All @@ -25,6 +29,19 @@ protected function render($partial)
->render();
}

protected function shouldRender(): bool
{
if ($this->params->has('when')) {
return $this->params->bool('when');
}

if ($this->params->has('unless')) {
return ! $this->params->bool('unless');
}

return true;
}

protected function viewName($partial)
{
$partial = str_replace('/', '.', $partial);
Expand Down
44 changes: 44 additions & 0 deletions tests/Tags/PartialTagsTest.php
Expand Up @@ -101,4 +101,48 @@ public function parameter_will_override_partial_front_matter()
$this->partialTag('mypartial', 'foo="baz"')
);
}

/** @test */
public function it_doesnt_render_partial_if_when_condition_is_false()
{
$this->viewShouldReturnRaw('mypartial', "---\nfoo: bar\n---\nthe partial content with {{ foo }}");

$this->assertEquals(
'',
$this->partialTag('mypartial', 'foo="baz" when="false"')
);
}

/** @test */
public function it_renders_partial_if_when_condition_is_true()
{
$this->viewShouldReturnRaw('mypartial', "---\nfoo: bar\n---\nthe partial content with {{ foo }}");

$this->assertEquals(
'the partial content with baz',
$this->partialTag('mypartial', 'foo="baz" when="true"')
);
}

/** @test */
public function it_doesnt_render_partial_if_unless_condition_is_true()
{
$this->viewShouldReturnRaw('mypartial', "---\nfoo: bar\n---\nthe partial content with {{ foo }}");

$this->assertEquals(
'',
$this->partialTag('mypartial', 'foo="baz" unless="true"')
);
}

/** @test */
public function it_renders_partial_if_unless_condition_is_false()
{
$this->viewShouldReturnRaw('mypartial', "---\nfoo: bar\n---\nthe partial content with {{ foo }}");

$this->assertEquals(
'the partial content with baz',
$this->partialTag('mypartial', 'foo="baz" unless="false"')
);
}
}