I am building a Javascript program which is loaded by an external include. Like this:
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
...html here....
<script defer>
myjs = document.createElement('script');
myjs.setAttribute('src', 'http://myapi.com/api/v1/get_the_js/');
myjs.setAttribute('type', 'text/javascript');
document.head.appendChild(myjs);
</script>
</body>
</html>
In Laravel I currently have the route going to this function:
class JSPluginController extends Controller
{
public function index()
{
$js = resource_path() . '/js/myjs.js';
return file_get_contents($js);
}
}
This works. However, I want to change myjs.js over to a blade template so I can use the power of blade.
The only way I have found to do this so far is to add script tags so that I can actually see js formatting in my IDE, but then it obviously breaks the returned output for the API. Here's what I have so far:
The endpoint routes here:
class JSPluginController extends Controller
{
public function js_blade()
{
return view('jsplugin/main');
}
}
and in /resources/views/jsplugin/main.blade.js:
<script>
.. my js goes here {{ $withBladeStuff }} ...
</script>
Is there a better way to do this?
It is worth noting that I also plan to break up my JS into multiple files, like abstracting them into various pieces as needed.
(Side note: My PHP formatting is PSR-12 compliant. No need to edit that, thanks.)