Skip to content

Instantly share code, notes, and snippets.

@alariva
Last active July 2, 2017 23:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alariva/d94b3570bf2f6efb1712f49b99d0de93 to your computer and use it in GitHub Desktop.
Save alariva/d94b3570bf2f6efb1712f49b99d0de93 to your computer and use it in GitHub Desktop.
Laravel ConsoleTVs/Charts adapter class for splitting script and html
<?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;
}
}
<?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'));
// Usage in your view
@section('section')
// ...
{!! $chartRender->html() !!}
// ...
@endsection
@push('scripts')
// ...
{!! $chartRender->script() !!}
// ...
@endpush
@ConsoleTVs
Copy link

Will keep an eye at this to add it to the original one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment