Skip to content

Commit

Permalink
add support for translation blocks in blade templates
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed Nov 18, 2016
1 parent 9437244 commit 7179935
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/Illuminate/View/Compilers/BladeCompiler.php
Expand Up @@ -546,7 +546,24 @@ protected function compileEndunless($expression)
*/
protected function compileLang($expression)
{
return "<?php echo app('translator')->get$expression; ?>";
if (is_null($expression)) {
return "<?php \$__env->startTranslation(); ?>";
} elseif ($expression[1] === '[') {
return "<?php \$__env->startTranslation{$expression}; ?>";
} else {
return "<?php echo app('translator')->get$expression; ?>";
}
}

/**
* Compile the endlang statements into valid PHP.
*
* @param string $expression
* @return string
*/
protected function compileEndlang()
{
return '<?php echo $__env->renderTranslation(); ?>';
}

/**
Expand Down
32 changes: 32 additions & 0 deletions src/Illuminate/View/Factory.php
Expand Up @@ -143,6 +143,13 @@ class Factory implements FactoryContract
*/
protected $pushStack = [];

/**
* The translation replacements for the translation being rendered.
*
* @var array
*/
protected $translationReplacements = [];

/**
* The number of active rendering operations.
*
Expand Down Expand Up @@ -851,6 +858,31 @@ public function yieldPushContent($section, $default = '')
return implode($this->pushes[$section]);
}

/**
* Start a translation block.
*
* @param array $replacements
* @return void
*/
public function startTranslation($replacements = [])
{
ob_start();

$this->translationReplacements = $replacements;
}

/**
* Render the current translation.
*
* @return string
*/
public function renderTranslation()
{
return $this->container->make('translator')->getFromJson(
trim(ob_get_clean()), $this->translationReplacements
);
}

/**
* Flush all of the section contents.
*
Expand Down
14 changes: 14 additions & 0 deletions tests/View/ViewFactoryTest.php
Expand Up @@ -285,6 +285,20 @@ public function testComponentHandling()
$this->assertEquals('title<hr> component Taylor', $contents);
}

public function testTranslation()
{
$container = new Illuminate\Container\Container;
$container->instance('translator', $translator = m::mock('StdClass'));
$translator->shouldReceive('getFromJson')->with('Foo', ['name' => 'taylor'])->andReturn('Bar');
$factory = $this->getFactory();
$factory->setContainer($container);
$factory->startTranslation(['name' => 'taylor']);
echo 'Foo';
$string = $factory->renderTranslation();

$this->assertEquals('Bar', $string);
}

public function testSingleStackPush()
{
$factory = $this->getFactory();
Expand Down

0 comments on commit 7179935

Please sign in to comment.