Created
April 4, 2019 10:38
-
-
Save fabricat/2cfda53c5f979da67300002615c0b871 to your computer and use it in GitHub Desktop.
Get all variable names defined in a Twig template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
tokens = $twig->tokenize($loader->getSourceContext('index.html')); | |
$templateVars = []; | |
while (!$tokens->isEOF()) { | |
$token = $tokens->next(); | |
if ($token->getType() === \Twig_Token::VAR_START_TYPE) { | |
$templateVars[] = $tokens->next()->getValue(); | |
$tokens->next(); | |
} | |
} |
It depends. If you have to check a template for missing vars, you have to check it outside the template.
Moreover, you can even report if there are unhandled vars in a template to make a sort of check before uploading like "unused declared var" in common programming languages.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is better to handle missing values INSIDE the template (but I didn't want to waste this piece of code)