How to set up Javascript AS a Blade template for use in an API endpoint?

Viewed 117

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.)

1 Answers

I solved this by adding just a couple of simple steps to accommodate my needs.

To clarify, this controller routes an api endpoint that is pulled into an external site as script like this:

<script defer>
    js = document.createElement('script');
    js.setAttribute('src', 'https://example.com/api/v1/get_js');
    js.setAttribute('type', 'text/javascript');
    document.head.appendChild(js);
</script>

So it has to pull javascript without the tags. However, editing the blade within my IDE doesn't like it because it's a blade.php file, and I want the automatic code styling for JS.

Therefore, I updated the controller to add a variable $included:

class JSPluginController extends Controller
{
    public function index()
    {
        $included = true;
        $env = \App::environment();

        return view('js/main', compact('included', 'env'));
    }
}

The $included variable then gets passed into the blade (/resources/views/js/main.blade.php), and this still allows my IDE to do its code formatting:

@if(!$included)
<script>
@endif
    let hello_world = "{{ $env }}";
    document.write("The environment is: " + hello_world);
@if(!$included)
</script>
@endif

This satisfies my needs beautifully! I can use all the power and control of blade, and still retain my code formatting. Happy coding.

Related