1

How do I validate a mustache template string in PHP? For example, if I pass

Hi {{#name}}{{name}}{{/name}}{{^name}}guest{{/name}}

and the validator should return valid, but if I pass

Hi {{#name}}{{name}}{{/name}}{{^name}}guest

it should return invalid.

Note I'd rather this to be done fully in PHP with no Mustache_Engine or any other 3rd party dependency.

Kousha
  • 32,871
  • 51
  • 172
  • 296
  • short answer: write your own Mustache Engine. (tip: it's easier and less error prone to just use an existing library) – Kaii Sep 12 '16 at 19:18

2 Answers2

0

Just compile it:

function validate($template) {
    $m = new Mustache_Engine;
    try {
        $m->getParser()->parse($m->getTokenizer()->scan($template));
        $valid = true;
    } catch (Mustache_Exception_SyntaxException $e) {
        $valid = false;
    }
    return $valid;
}
Alex Blex
  • 34,704
  • 7
  • 48
  • 75
0

It's not possible to correctly validate all valid mustache templates without building a mustache parser. There is no regular expression shortcut. You need an actual parser.

If you're okay with some false negatives (and some false positives) you could build something to validate a subset of them. Or you can build a proper parser. But your best bet is to use mustache.php to parse it, as indicated in other answers.

Why are you trying to do this without any dependencies?

bobthecow
  • 5,047
  • 25
  • 27