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 Twig switch/case extension #6

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,23 @@ Can also be used with the BEM Function:
<div {{ add_attributes(additional_attributes) }}></div>
```

### Switch Case Twig Extension

This adds the ability to do a `switch/case` function from within Twig templates. To use:

```twig
{% switch content.field_name.0 %}
{% case "text" %}
<p>This appears if the field name value is set to "text"</p>
{% case "image" %}
<p>This appears if the field name value is set to "image"</p>
{% default %}
<p>The field text did not match any case.</p>
{% endswitch %}
```

Note that the `switch`, `endswitch`, and `case` tags are required and the `default` is optional.

## Development

---
Expand Down
4 changes: 4 additions & 0 deletions emulsify_tools.services.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,7 @@ services:
- { name: drush.command }
emulsify_tools.subtheme_generator:
class: Drupal\emulsify_tools\SubThemeGenerator
emulsify_tools.twig.switch:
class: Drupal\emulsify_tools\SwitchExtension
tags:
- { name: twig.extension }
21 changes: 21 additions & 0 deletions src/SwitchExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Drupal\emulsify_tools;

use Twig\Extension\AbstractExtension;

/**
* Creates a new switch case extension for Twig.
*/
class SwitchExtension extends AbstractExtension {

/**
* Gets token parsers.
*/
public function getTokenParsers() {
return [
new SwitchTokenParser(),
];
}

}
66 changes: 66 additions & 0 deletions src/SwitchNode.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace Drupal\emulsify_tools;

use Twig\Compiler;
use Twig\Node\Node;

/**
* Class SwitchNode. Based on Craft CMS.
*
* @see https://github.com/craftcms/cms.
*/
class SwitchNode extends Node {

/**
* {@inheritdoc}
*/
public function compile(Compiler $compiler): void {
$compiler
->addDebugInfo($this)
->write('switch (')
->subcompile($this->getNode('value'))
->raw(") {\n")
->indent();

foreach ($this->getNode('cases') as $case) {
/** @var Twig\Node\Node $case */
/* The 'body' node may have been removed by Twig if it was an empty text
* node in a sub-template, outside of any blocks.
*/
if (!$case->hasNode('body')) {
continue;
}

foreach ($case->getNode('values') as $value) {
$compiler
->write('case ')
->subcompile($value)
->raw(":\n");
}

$compiler
->write("{\n")
->indent()
->subcompile($case->getNode('body'))
->write("break;\n")
->outdent()
->write("}\n");
}

if ($this->hasNode('default')) {
$compiler
->write("default:\n")
->write("{\n")
->indent()
->subcompile($this->getNode('default'))
->outdent()
->write("}\n");
}

$compiler
->outdent()
->write("}\n");
}

}
120 changes: 120 additions & 0 deletions src/SwitchTokenParser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?php

namespace Drupal\emulsify_tools;

use Twig\Error\SyntaxError;
use Twig\Node\Node;
use Twig\Token;
use Twig\TokenParser\AbstractTokenParser;

/**
* Class SwitchTokenParser that parses {% switch %} tags. Based on Craft CMS.
*
* @see https://github.com/craftcms/cms.
*/
class SwitchTokenParser extends AbstractTokenParser {

/**
* {@inheritdoc}
*/
public function getTag(): string {
return 'switch';
}

/**
* {@inheritdoc}
*/
public function parse(Token $token): SwitchNode {
$lineno = $token->getLine();
$parser = $this->parser;
$stream = $parser->getStream();

$nodes = [
'value' => $parser->getExpressionParser()->parseExpression(),
];

$stream->expect(Token::BLOCK_END_TYPE);

// Trim whitespace between the {% switch %} and first {% case %} tag.
while ($stream->getCurrent()->getType() == Token::TEXT_TYPE && trim($stream->getCurrent()->getValue()) === '') {
$stream->next();
}

$stream->expect(Token::BLOCK_START_TYPE);

$expressionParser = $parser->getExpressionParser();
$cases = [];
$end = FALSE;

while (!$end) {
$next = $stream->next();

switch ($next->getValue()) {
case 'case':
$values = [];
while (TRUE) {
$values[] = $expressionParser->parsePrimaryExpression();
// Multiple allowed values?
if ($stream->test(Token::OPERATOR_TYPE, 'or')) {
$stream->next();
}
else {
break;
}
}
$stream->expect(Token::BLOCK_END_TYPE);
$body = $parser->subparse([$this, 'decideIfFork']);
$cases[] = new Node([
'values' => new Node($values),
'body' => $body,
]);
break;

case 'default':
$stream->expect(Token::BLOCK_END_TYPE);
$nodes['default'] = $parser->subparse([$this, 'decideIfEnd']);
break;

case 'endswitch':
$end = TRUE;
break;

default:
throw new SyntaxError(sprintf('Unexpected end of template. Twig was looking for the following tags "case", "default", or "endswitch" to close the "switch" block started at line %d)', $lineno), -1);
}
}

$nodes['cases'] = new Node($cases);

$stream->expect(Token::BLOCK_END_TYPE);

return new SwitchNode($nodes, [], $lineno, $this->getTag());
}

/**
* Decide IF Fork.
*
* @param Twig\Token $token
* The token to parse.
*
* @return bool
* Returns if one of the tokens is part of this switch statement.
*/
public function decideIfFork(Token $token): bool {
return $token->test(['case', 'default', 'endswitch']);
}

/**
* Decides if end of switch statement.
*
* @param Twig\Token $token
* The token to parse.
*
* @return bool
* Returns if we are at the end of the switch statement.
*/
public function decideIfEnd(Token $token): bool {
return $token->test(['endswitch']);
}

}
Loading