Skip to content

Commit 659dc57

Browse files
committed
Blade Directive - #3
1 parent 4de857e commit 659dc57

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

docs/readme.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,14 @@ $chart->options($options);
106106

107107
$chart->toJson();
108108
```
109+
110+
### Blade
111+
It is also possible to use the Blade Directive and generate the chart canvas
112+
```blade
113+
@chartjs('element_id', $chart)
114+
```
115+
116+
109117
### Config class
110118
To configure your chart you can use the `Config` class directly or helpers
111119
like `Dataset` or `Options`.

src/Chart.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,4 +118,27 @@ public function beginAtZero()
118118

119119
return $this;
120120
}
121+
122+
/**
123+
* @param string $element
124+
* @param Chart|null $chart
125+
* @param string $height
126+
* @param string $width
127+
*
128+
* @return string
129+
*/
130+
public function toHtml(string $element, Chart $chart = null)
131+
{
132+
if ($chart === null) {
133+
$chart = $this;
134+
}
135+
136+
return '<canvas id="' . $element . '"></canvas>
137+
<script>
138+
new Chart(
139+
document.getElementById("' . $element . '").getContext("2d"),
140+
' . $chart->toJson() . '
141+
);
142+
</script>';
143+
}
121144
}

src/ChartServiceProvider.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Bbsnly\ChartJs;
44

5+
use Illuminate\Support\Facades\Blade;
56
use Illuminate\Support\ServiceProvider;
67

78
class ChartServiceProvider extends ServiceProvider
@@ -13,7 +14,9 @@ class ChartServiceProvider extends ServiceProvider
1314
*/
1415
public function boot()
1516
{
16-
//
17+
Blade::directive('chartjs', function ($expression) {
18+
return "<?php echo app(\Bbsnly\ChartJs\Chart::class)->toHtml($expression); ?>";
19+
});
1720
}
1821

1922
/**

0 commit comments

Comments
 (0)