Skip to content

Added functionality to generate hash of values from template #81

Closed
wants to merge 1 commit into from

2 participants

@anyonecancode

Hey - I had a need to do a reverse Mustache - take a template, and generate the hash of expected values. Useful for when a developer needs to quickly and easily know what values a template takes. I added this feature, but this is my first attempt at a pull request, so I'm not sure i'm doing this right - I originally did it in the master branch of my fork, but then realized I should maybe do it in the branch feature/makeHash. Not sure if pull requests are per branch or per repo, so I'm not entirely sure what you'll receive here.

Also, I wasn't sure what kind of unit tests would be appropriate, so that's missing. The example is a viewable example, which is different from what your examples look like - so feel free to take or leave that.

Hope this feature is helpful to others!

@bobthecow
Owner

Sorry to make a moving target for you, but you should check out the 2.0-dev version in the dev branch. The bad news is everything changed. The good news is, it means you can actually use a full parser (rather than regex matching) to generate your hash of values. In your case, you'd do something like...

<?php
$m = new Mustache;
$tree = $m->parse('{{#foo}}{{bar}}{{/foo}}');

The value in $tree is a parse tree of the template, which you can then walk and extract values:

<?php

use Mustache\Mustache;
use Mustache\Tokenizer;

class MustacheHasher {
    public function __construct() {
        $this->mustache = new Mustache;
    }

    public function makeHash($template) {
        $tree = $this->mustache->parse($template);

        return $this->walk($tree);
    }

    private function walk(array $tree) {
        $hash = array();
        foreach ($tree as $node) {
            // extract values
            if (is_array($node)) {
                switch ($node[Tokenizer::TYPE]) {
                    // values
                    case Tokenizer::T_ESCAPED:
                    case Tokenizer::T_UNESCAPED:
                    case Tokenizer::T_UNESCAPED_2:
                        $hash[$node[Tokenizer::NAME]] = '';
                        break;

                    // sections
                    case Tokenizer::T_SECTION:
                    case Tokenizer::T_INVERTED:
                        $hash[$node[Tokenizer::NAME]] = $this->walk($node[Tokenizer::NODES]);
                        break;
                }
            }
        }

        return $hash;
    }
}
@bobthecow
Owner

Closing as this can no longer be merged (and should be way easier in Mustache v2.0).

@bobthecow bobthecow closed this Oct 27, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.