Last active
January 27, 2019 01:44
-
-
Save dib258/2321ae67b58ed25d9c9f941eae04f288 to your computer and use it in GitHub Desktop.
Custom Blade directive that currently need to pass variable name by argument
This file contains hidden or 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 | |
namespace App\Providers; | |
use Illuminate\Support\Facades\Blade; | |
use Illuminate\Support\ServiceProvider; | |
use Illuminate\View\Compilers\BladeCompiler; | |
class AppServiceProvider extends ServiceProvider | |
{ | |
/** | |
* Bootstrap any application services. | |
* | |
* @return void | |
*/ | |
public function boot() | |
{ | |
} | |
/** | |
* Custom Blade directive | |
* | |
* @return void | |
*/ | |
public function register() | |
{ | |
$this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) { | |
$bladeCompiler->directive('translation', function($arguments) { | |
list($staticTexts, $staticName) = explode(',', $arguments.','); | |
return "<?php if ({$staticTexts}->has({$staticName})) { echo {$staticTexts}->get({$staticName})->translate()->value; } else { echo {$staticName}; } ?>"; | |
}); | |
}); | |
} | |
} |
This file contains hidden or 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 | |
// Trait that generate the Collection to share with the view | |
trait DynamicTranslatable | |
{ | |
protected function queryStaticTexts($pageName) { | |
$staticTexts = StaticText::join('pages', 'page_id', '=', 'pages.id')->where('pages.name', '=', $pageName)->select('static_texts.*')->get(); | |
$staticTexts = $staticTexts->keyBy(function ($item) { | |
return strtolower($item->name); | |
}); | |
View::share('staticTexts', $staticTexts); | |
} | |
} |
This file contains hidden or 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
<!-- Template --> | |
@translation($staticTexts, 'value') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment