Skip to content

Instantly share code, notes, and snippets.

@matthew-inamdar
Last active July 13, 2018 14:22
Show Gist options
  • Save matthew-inamdar/290cbd62901b464fef3f069beef65d03 to your computer and use it in GitHub Desktop.
Save matthew-inamdar/290cbd62901b464fef3f069beef65d03 to your computer and use it in GitHub Desktop.
Add custom file extensions to blade
<?php // app/Providers/BladeServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class BladeServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Register *.blade.yaml files as blade views.
resolve(\Illuminate\View\Factory::class)->addExtension('blade.yaml', 'blade');
}
}
<?php // app/Http/Controllers/DocsController.php
namespace App\Http\Controllers;
use Illuminate\Http\Response;
class DocsController extends Controller
{
/**
* @param string $path
*
* @return \Illuminate\Http\Response
* @throws \Throwable
*/
public function show(string $path)
{
// Parse the URL path so Laravel can find the corresponding view.
$path = str_replace('.yaml', '', $path);
$view = str_replace('/', '.', $path);
$view = 'docs.' . $view;
$pathParts = explode('/', $path);
$filename = array_last($pathParts);
// 404 if the view does not exist.
if (!view()->exists($view)) {
abort(Response::HTTP_NOT_FOUND);
}
// Parse the YAML Blade template and retrieve the string contents.
$yaml = view($view)->render();
return response()->make($yaml, Response::HTTP_OK, [
'Content-Type' => 'application/x-yaml',
'Content-Disposition' => sprintf('inline; filename="%s.yaml"', $filename),
]);
}
}
# resources/views/example.blade.yaml
name: Example
version: 1.0
supported:
- OAuth 2.0
- API Token
<?php // routes/web.php
use Illuminate\Facades\Route;
Route::get('/docs/{path}', 'DocsController@show')
->where('path', '.*(.yaml)')
->name('docs.show');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment