0

in my case i have a controller that it send for me the title , to the view , but i want to send the tittle and the body of the article both , i have tried to send them from the controller but it doesn't work for me

how can i send them both from the controller (title and body) ?

here is tmy controller

 public function myPage() {
    $data = \Drupal::service('myservice.ran');
    $dataService = $data->getArticles();
    return $this->renderMyPage($dataService);
  }
  function renderMyPage($articleObjects) {
    $articles = [];
    foreach ($articleObjects as $article) {
      $articles[] = [
        '#type' => 'html_tag',
        '#html_tag' => 'h2',
        '#value' => [$article->title->value,$article->body->value],
        '#cache' => [
          'tags' => $article->getCacheTags(),
        ],
      ];
    }
    return $articles;
  }
2
  • You want both the title and the body inside the h2 tag? #value only takes strings. See class HtmlTag. So you either concat both values or you build a different render array. Probably best would be you use hook_theme to add your own template.
    – leymannx
    Commented Jun 29, 2020 at 6:09
  • 1
    @leymannx. instead of #value you could put render children (array keys not starting with #) in html_tag and so create a nested render array, for example a #plain_text for the title and '#type' => 'processed_text' for the body to output the field values safely.
    – 4uk4
    Commented Jun 29, 2020 at 6:19

1 Answer 1

2

What I suggest is the this solution, create a custom template, for your page, in controller pass the data to the twig template.

public function myPage() {

    $data = \Drupal::service('myservice.ran');
    $dataService = $data->getArticles();
    $articles = [];
    foreach ($dataService as $article) {
      $articles[] = [
        'title' => $article->title->value,
        'body' => $article->body->value,
      ];
    }
    $build = [
      '#theme' => 'my_template',
      '#data' => [
        'articles' => $articles,
        'whatelse' => "what esle I want"
      ],
      '#cache' => ['max-age' => 0],
    ];
    $output = \Drupal::service('renderer')->renderRoot($build);
    $response = new Response();
    $response->setContent($output);
    return $response;
  }

then all the data will be available on data in your custom twig template. ( you can change its name to whatever you want).

just be sure you clear the cache when you create your custom template.

A helper article

1
  • Why not just return $build, instead of rendering it in the controller and returning the rendered output?
    – Elin Y.
    Commented Nov 4, 2020 at 13:09

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.