Variable "tags" does not exist.

Par Anouchka25, il y a 7 ans


Bonjour

Je ne comprends pourquoi l'erreur est que la variable "tags" n'existe pas, pourtant je l'ai bien défini dans le controller comme ceci :

public function tagsliste(TagRepository $tagRepository): Response { return $this->render('post/_all_tags.html.twig', ['tags' => $tagRepository->findAll()]); }

post/_all_tags.html.twig :

<div class="tags-list"> {% for tag in tags %} <a href="#">{{ tag.name }}</a> {% endfor %} </div><!-- .tags-list -->

Je vous remercie de votre aide !

5 réponses

Digivia, il y a 7 ans

Bonjour Anouchka,
Tout d'abord, quel est l'intérêt de passer un repo en param de ton controller?

public function tagsliste(): Response { $tags = $this->getDoctrine()->getManager()->getRepository('App/Tags')->findAll(); return $this->render('post/_all_tags.html.twig', ['tags' => $tags]); }

Ca me paraît + simple...
Mais bon ca ne résoud pas le pb. A priori, je dirais que tes tags sont vides, donc aucun passage dans la boucle for de ton twig ?
Essaye un dump($tags) dans ton controller pour vérifier...

Anouchka25, il y a 7 ans

Quand je met ceci, j'ai bien la liste des tags:

public function index(TagRepository $tagRepository): Response { return $this->render('post/index.html.twig', [ 'tags' => $tagRepository->findAll()]); }

post/index.html.twig :

{% extends 'base.html.twig' %} {% block title %}Hello{% endblock %} {% block body %} <div class="tags-list"> {% for tag in tags %} <a href="#">{{ tag.name }}</a> {% endfor %} </div><!-- .tags-list --> {% endblock %}
Anouchka25, il y a 7 ans

Merci pour le lien.
J'ai fait ceci :
Dans App\Controller\BlogController.php

public function tagAction(TagRepository $tagRepository): Response { return $this->render('post/_all_tags.html.twig', ['tags' => $tagRepository->findAll()]); }

post/_all_tags.html.twig :

{% for tag in tags %} <a href="#"> {{ tag.name }} </a> {% endfor %}

post/sidebar.html.twig :

<div class="tags-list"> {{ render(controller('App\\Controller\\BlogController::tagAction')) }} </div><!-- .tags-list -->

Mais j'obtiens cette erreur :

An exception has been thrown during the rendering of a template ("Controller "App\Controller\BlogController" does neither exist as service nor as class").
Digivia, il y a 7 ans

Dans post/sidebar.html.twig :

{{ render(controller('App\\Controller\\BlogController::tagAction')) }}

à remplacer par :

{{ render(controller('App:Controller:BlogController::tag', {'tagRepository ': 'valeur de ton TagRepository'})) }}

Il faut enlever le "action" à la fin du nom de ton controleur (c'est une convention). Mais tu vas avoir une autre erreur.
En effet, quelle valeur affecter à tagRepository, puisque tu ne l'as pas dans ton template twig ?...
Perso je reverrais mon controleur comme je te l'ai indiqué un peu plus haut (sans le repo en paramètre)...