Rendering Blade views with Controller data in a function

I am trying to AJAX load more content using Blade templates. I managed to successfully generate html from a template using \App\template('partials.content-single') in a function and load that via javascript and REST API, but then all the variables were missing. I am using Controller methods which return data and are accessible as snake_case variables in the template.

I know I can also pass data to a template like so \App\template('partials.content-single', $data), but I cannot find a way to gather all the variables generated from the view Controller. Or is there another way to properly render a Blade template after the initial load and get the html?

Any help and examples are much appreciated! :slight_smile:

Hey @kaido - off the top of my head, you may need to call the relevant controller method(s) from your AJAX action to generate the data you need, then pass that to your template using the syntax you showed in your post.

Well, I got to expose the data from the App controller using this code from filters.php:

$template = 'views/partials/content-single';
$data = collect(get_body_class())->reduce(function ($data, $class) use ($template) {
    return apply_filters("sage/template/{$class}/data", $data, $template);
}, []);

$response['html'] = \App\template('partials.content-single', $data);

But, not sure how to get the data from the Single controller in addition as it would on a normal page load. Maybe the $template variable must be something different?

Hey @kaido - I don’t think the single controller will be running and populating the data on an AJAX request , since the single template isn’t being requested. I think you’ll need to call the relevant single controller method directly in your AJAX handler rather than relying on the automatic method used for non-AJAX requests that load a template.

Alright, thanks for the answer!

1 Like