I am trying to grasp the MVC/Symphony integraton of Drupal and am making use of the controllers. My controller has a function named "returnHTML" which is called by a normal XMLHttpRequest. Problem is I do not know how to generate the HTML. I could use a theme, but implementing a theme feels a little bit too complicated for this simple task. I want a HTML-fragment, ergo what you see is what you get, not a complete webpage.

Is there a way to return HTML just specifying where a twig is and have this twig-file injected with data in the "returnHTML"-function immediately? Also is there a recommended class (like Symphonys JsonResponse) which will help with the headers?

1 Answer 1


Since we are fairly new in the Drupal 8 jungle I'll give some feedback how I fixed this. Be aware this is probably not the best solution.

Using a controller I included this function:

     * Inspiration page action
    function inspiration(){
        $twig = \Drupal::service('twig');
        $template = $twig->loadTemplate(drupal_get_path('module', 'experimental') . '/templates/inspiration.html.twig');
        echo $template->render([]);

This works fine, allthough it is not very beautiful.

  • Worked for me almost 3 years later. It would great to have a simple solution like this but with the "regular" render array with '#theme'. All my trials and errors (yes there's a LOT of that in Drupal) I wasn't able to render only the portion of what I needed. I always got the ENTIRE page, including the admin menus... Sep 11, 2017 at 17:53
  • Ha found it: drupal.stackexchange.com/questions/231188/… which is a much nicer solution. Sep 11, 2017 at 17:57
  • Hi, how you send variables to twig template? @Undrium
    – tasqyn
    Aug 21, 2019 at 6:04

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.