0

I'm trying to check through Twig if there is a request in order to show the results of my searchBar, in Twig, ONLY if there is a request.

I found old symfony docs on app.request, but it doesn't seem to work for my 5.2 Symfony Project (here is my twig template) :

{% if app.request %}
    <h3 class="main-header_h3">Résultats de la recherche</h3>
    <hr>
    <div class="grid">
        {% for product in products %}
            {% include 'product/_card.html.twig' with {product: product} only %}
        {% endfor %}
    </div>
    <hr>
{%endif %}

Problem here is that my {% if app.request %} isn't being interpreted, so I get my whole product database coming on my view. If you need any more code, let me know (Controller/Repository...) but the request definitely works, it's just my rendering in Twig that gives me trouble using that if.

MilanDemoniack
  • 531
  • 4
  • 12
  • 1
    Isn't there always a request? Are you trying to check the request method (GET, POST, etc.)? – Arleigh Hix Feb 12 '21 at 18:45
  • There is indeed always an `app.request` that would at least contain the URI accessed. https://stackoverflow.com/a/20329384/2123530 To get yourself out of this: [`dump`](https://twig.symfony.com/doc/2.x/functions/dump.html) it. `({ dump(app.request) }}` will help you compare what is in that variable/object and what you did expect there. – β.εηοιτ.βε Feb 12 '21 at 19:01
  • Do you want to do something like this: `{% if app.request.query.get('search', null) %}` where `search` is the url param? – bechir Feb 13 '21 at 02:55
  • @bechir, yes, that's exactly what I'm trying to do. My URL parameter is 'search', and I want to to check using Twig if it's there or not, and if it is, then `include` a partial i've made. – MilanDemoniack Feb 13 '21 at 08:37

1 Answers1

0

Thanks to @bechir, the solution to checking if my URL has a 'search' parameter in it using TWIG is :

{% if app.request.query.get('search', null) %} where search is the url parameter. (from : bechir)

So this is what it now looks like, and I do have my partial product/_card.html.twig loaded only when there's a URL parameter search:

{% if app.request.query.get('search', null) %}
    <h3 class="main-header_h3">Résultats de la recherche :</h3>
    <hr>
    <div class="grid">
        {% for product in products %}
            {% include 'product/_card.html.twig' with {product: product} only %}
        {% endfor %}
    </div>
    <hr>
{% endif %}
MilanDemoniack
  • 531
  • 4
  • 12