Skip to content

Instantly share code, notes, and snippets.

@fabricat
Created April 4, 2019 10:38
Show Gist options
  • Save fabricat/2cfda53c5f979da67300002615c0b871 to your computer and use it in GitHub Desktop.
Save fabricat/2cfda53c5f979da67300002615c0b871 to your computer and use it in GitHub Desktop.
Get all variable names defined in a Twig template
<?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();
}
}
@fabricat
Copy link
Author

fabricat commented Apr 4, 2019

It is better to handle missing values INSIDE the template (but I didn't want to waste this piece of code)

@mindcreations
Copy link

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