Compile Blade strings and Blade custom directives (integrate with AngularJs)
<?php
namespace App\Modules\Tenant\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests;
class TenantController extends Controller {
public function index($tenant) {
try {
$data = [
'data' => [
'tenant' => $tenant,
'config' => $config,
'estabelecimento' => $estabelecimento,
'apiURL' => env('API_URL')
]
];
//compile string (database)
echo compileBlade("
<!DOCTYPE html>
<html ng-app='sampleApp'>
<body>
<h1>Hello <% teste %></h1>
<input type='text' ng-model='teste'>
<% usuario %>
@ngValue('usuario.nome')
@ngValue('usuario.email')
<h1>Compilando Blade</h1>
@estabelecimento('telefone')
@estabelecimento('email')
<script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js\"></script>
<script>
//change interpolate symbol
angular.module('sampleApp', [], function(\$interpolateProvider) {
\$interpolateProvider.startSymbol('<%');
\$interpolateProvider.endSymbol('%>');
});
</script>
</body>
</html>
", $data);
} catch (\Exception $e) {
dd($e->getMessage());
return view('welcome');
}
}
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class HelperServiceProvider extends ServiceProvider
{
protected $helpers = [
// Add your helpers in here
];
/**
* Bootstrap the application services.
*/
public function boot()
{
//
}
/**
* Register the application services.
*/
public function register()
{
//registrando helpers da aplicação
foreach (glob(app_path().DIRECTORY_SEPARATOR.'Helpers'.DIRECTORY_SEPARATOR.'*.php') as $filename){
require_once($filename);
}
//registrando helpers dos módulos
foreach (glob(app_path().DIRECTORY_SEPARATOR.'Modules'.DIRECTORY_SEPARATOR.'*'.DIRECTORY_SEPARATOR."Helpers".DIRECTORY_SEPARATOR."*.php") as $filename){
require_once($filename);
}
}
}
<?php
/**
* Compila uma string blade com as variáveis
* @param $string
* @param array $args
* @return string
* @throws Exception
*/
function compileBlade($string,array $args=array()){
$generated = Blade::compileString($string);
ob_start(); extract($args,EXTR_SKIP);
try {
eval('?>'.$generated);
} catch (\Exception $e) {
ob_get_clean(); throw $e;
}
$content = ob_get_clean();
return $content;
}
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Blade::directive('estabelecimento', function ($key) {
return '{{$data[\'estabelecimento\']['.$key.'] or ""}}';
});
Blade::directive('nomeEstabelecimento', function ($empty="") {
return '{{$data[\'estabelecimento\'][\'fatasia\'] or '.$empty.' }}';
});
Blade::directive('ngValue', function ($value) {
return '<input type=\'text\' ng-model={{'.$value.'}}>';
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}