-2

Within my module I have a button that calls an ajax request. The controller for this request is to collect some data, then render a Twig template using that data.

Using Drupal 10, how do I render the data/twig file, assign it to a variable, then send it back so the JS script can then place the code in the page?

Thanks.

3
  • Please edit the question to add the code you've written so far, what you expect it to do, and where it's failing specifically, plus any error messages you see. To make a good question for this site it's important we can understand what the exact problem is, otherwise any answer would just be a vague end-to-end tutorial, which doesn't suit the Q+A format here
    – Clive
    Jan 3 at 16:25
  • No extra code necessary. In the past Drupal 7 used a method - render() - I need to know the new way Drupal 10 does this so I can return the marked up template back to the ajax calling the controller.
    – Cy Jobes
    Jan 3 at 16:45
  • 1
    See drupal.stackexchange.com/questions/231188/… for some examples. I’d personally recommend following drupal.stackexchange.com/a/255476/2800 rather than the accepted answer. The accepted answer isn’t necessarily wrong, but using the AjaxCommand classes is a much better solution
    – Clive
    Jan 3 at 16:49

1 Answer 1

1

This is how I got it to work. Thanks to Angrytoast on Slack for the pointer!

public function paginateListing(Request $request) {
$rc = new RemindersController();
\Drupal::service('page_cache_kill_switch')->trigger();
$activeReminders = $rc->getAllActiveReminders($request->get('numrows'), $request->get('goto'));
$tableData = $rc->getReminderStatus($activeReminders);
$build = [
  '#theme' => 'rmdrs_table_listing',
  '#activeReminders' => $tableData,
  '#pagination' => array(
    'page_now' => (int) $_SESSION['rmdrs']['pager']['page_now'],
    'next_page' => (int) $_SESSION['rmdrs']['pager']['next_page'],
    'previous_page' => (int) $_SESSION['rmdrs']['pager']['previous_page'],
  ),
];

$output = \Drupal::service('renderer')->render($build);
return new JsonResponse($output);

}

The service is what I needed, along with building a $build array. I also had to create an entry in my .module file's hook_theme method.

'rmdrs_table_listing' => array(
  'variables' => array(
    'activeReminders' => null,
    'pagination' => null,
  ),
),
1
  • If the render process is final and you return the result in a response use \Drupal::service('renderer')->renderRoot($build). Otherwise, the controller causes an exception if the build array contains cache data or libraries. render() is only for rendering at the theming level.
    – 4uk4
    Jan 4 at 7:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.