Skip to content

Commit

Permalink
Anchor dot notation context: {{ .foo }}
Browse files Browse the repository at this point in the history
1. Given that {{ . }} resolves as the top of the context stack;
2. And when any falsey segment in a dotted name is encountered, the whole name yields '';
3. A name like {{ .name }} should imply {{ [top of stack].name }};
4. Thus, it must resolve as truthy only if a member of the top of the context stack matches name.

See mustache/spec#52
  • Loading branch information
bobthecow committed Aug 15, 2015
1 parent ba028d1 commit 5ab5fc6
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/Mustache/Context.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,12 @@ public function findDot($id)
{
$chunks = explode('.', $id);
$first = array_shift($chunks);
$value = $this->findVariableInStack($first, $this->stack);

if ($first === '') {
$value = $this->last();
} else {
$value = $this->findVariableInStack($first, $this->stack);
}

foreach ($chunks as $chunk) {
if ($value === '') {
Expand Down
43 changes: 43 additions & 0 deletions test/Mustache/Test/ContextTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,49 @@ public function testAccessorPriority()
$this->assertEquals('win', $context->find('baz'), 'ArrayAccess stands alone');
$this->assertEquals('win', $context->find('qux'), 'ArrayAccess beats private property');
}

public function testAnchoredDotNotation()
{
$context = new Mustache_Context();

$a = array(
'name' => 'a',
'number' => 1,
);

$b = array(
'number' => 2,
'child' => array(
'name' => 'baby bee',
),
);

$c = array(
'name' => 'cee',
);

$context->push($a);
$this->assertEquals('a', $context->find('name'));
$this->assertEquals('a', $context->findDot('.name'));
$this->assertEquals(1, $context->find('number'));
$this->assertEquals(1, $context->findDot('.number'));

$context->push($b);
$this->assertEquals('a', $context->find('name'));
$this->assertEquals(2, $context->find('number'));
$this->assertEquals('', $context->findDot('.name'));
$this->assertEquals(2, $context->findDot('.number'));
$this->assertEquals('baby bee', $context->findDot('child.name'));
$this->assertEquals('baby bee', $context->findDot('.child.name'));

$context->push($c);
$this->assertEquals('cee', $context->find('name'));
$this->assertEquals('cee', $context->findDot('.name'));
$this->assertEquals(2, $context->find('number'));
$this->assertEquals('', $context->findDot('.number'));
$this->assertEquals('baby bee', $context->findDot('child.name'));
$this->assertEquals('', $context->findDot('.child.name'));
}
}

class Mustache_Test_TestDummy
Expand Down

0 comments on commit 5ab5fc6

Please sign in to comment.