Last active
July 2, 2017 23:22
-
-
Save alariva/d94b3570bf2f6efb1712f49b99d0de93 to your computer and use it in GitHub Desktop.
Laravel ConsoleTVs/Charts adapter class for splitting script and html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* A possible solution to | |
* https://github.com/ConsoleTVs/Charts/issues/196 | |
* while keeping blade files clean | |
* | |
*/ | |
namespace App\Utils\Charts; | |
use ConsoleTVs\Charts\Builder\Chart; | |
class ChartRender | |
{ | |
protected $script; | |
protected $html; | |
private $chart; | |
public function __construct(Chart $chart) | |
{ | |
$this->chart = $chart; | |
} | |
public function script() | |
{ | |
if (!$this->script) { | |
$this->split(); | |
} | |
return $this->script; | |
} | |
public function html() | |
{ | |
if (!$this->html) { | |
$this->split(); | |
} | |
return $this->html; | |
} | |
public function split() | |
{ | |
$render = $this->chart->render(); | |
$scriptEnds = strrpos($render, '</script>') + strlen('</script>'); | |
$this->script = substr($render, 0, $scriptEnds); | |
$this->html = substr($render, $scriptEnds); | |
return $this; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// ... | |
// Wherever you are building your chart, maybe your Controller | |
$chart = Charts::create('line', 'highcharts') | |
->title('My nice chart') | |
->labels(['First', 'Second', 'Third']) | |
->values([5,10,20]) | |
->dimensions(0,500); | |
$chartRender = new ChartRender($chart); | |
return view('view', compact('chartRender')); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Usage in your view | |
@section('section') | |
// ... | |
{!! $chartRender->html() !!} | |
// ... | |
@endsection | |
@push('scripts') | |
// ... | |
{!! $chartRender->script() !!} | |
// ... | |
@endpush |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Will keep an eye at this to add it to the original one