Skip to content

Commit

Permalink
[8.x] Introduce @js() directive (#39522)
Browse files Browse the repository at this point in the history
* [8.x] Introduce `@js()` directive

* Update CompilesJs.php

* Update to match new name

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
inxilpro and taylorotwell authored Nov 15, 2021
1 parent 0e9ff79 commit 31da25c
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/Illuminate/View/Compilers/BladeCompiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class BladeCompiler extends Compiler implements CompilerInterface
Concerns\CompilesIncludes,
Concerns\CompilesInjections,
Concerns\CompilesJson,
Concerns\CompilesJs,
Concerns\CompilesLayouts,
Concerns\CompilesLoops,
Concerns\CompilesRawPhp,
Expand Down
22 changes: 22 additions & 0 deletions src/Illuminate/View/Compilers/Concerns/CompilesJs.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace Illuminate\View\Compilers\Concerns;

use Illuminate\Support\Js;

trait CompilesJs
{
/**
* Compile the "@js" directive into valid PHP.
*
* @param string $expression
* @return string
*/
protected function compileJs(string $expression)
{
return sprintf(
"<?php echo \%s::from(%s)->toHtml() ?>",
Js::class, $this->stripParentheses($expression)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use JsonSerializable;
use PHPUnit\Framework\TestCase;

class SupportJsStringTest extends TestCase
class SupportJsTest extends TestCase
{
public function testScalars()
{
Expand Down
30 changes: 30 additions & 0 deletions tests/View/Blade/BladeJsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace Illuminate\Tests\View\Blade;

class BladeJsTest extends AbstractBladeTestCase
{
public function testStatementIsCompiledWithoutAnyOptions()
{
$string = '<div x-data="@js($data)"></div>';
$expected = '<div x-data="<?php echo \Illuminate\Support\Js::from($data)->toHtml() ?>"></div>';

$this->assertEquals($expected, $this->compiler->compileString($string));
}

public function testJsonFlagsCanBeSet()
{
$string = '<div x-data="@js($data, JSON_FORCE_OBJECT)"></div>';
$expected = '<div x-data="<?php echo \Illuminate\Support\Js::from($data, JSON_FORCE_OBJECT)->toHtml() ?>"></div>';

$this->assertEquals($expected, $this->compiler->compileString($string));
}

public function testEncodingDepthCanBeSet()
{
$string = '<div x-data="@js($data, JSON_FORCE_OBJECT, 256)"></div>';
$expected = '<div x-data="<?php echo \Illuminate\Support\Js::from($data, JSON_FORCE_OBJECT, 256)->toHtml() ?>"></div>';

$this->assertEquals($expected, $this->compiler->compileString($string));
}
}

0 comments on commit 31da25c

Please sign in to comment.