How can I render more than one field value in the controller?
-
25-02-2021 - |
Question
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;
}
Solution
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange