Skip to content

Instantly share code, notes, and snippets.

@dib258
Last active January 27, 2019 01:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dib258/2321ae67b58ed25d9c9f941eae04f288 to your computer and use it in GitHub Desktop.
Save dib258/2321ae67b58ed25d9c9f941eae04f288 to your computer and use it in GitHub Desktop.
Custom Blade directive that currently need to pass variable name by argument
<?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}; } ?>";
});
});
}
}
<?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);
}
}
<!-- Template -->
@translation($staticTexts, 'value')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment