Access get parameters in Shopware's storefront .twig

How to access standard php $_GET parameters from the Shopware storefront .twig files. E.g. The URL query string parameters.

159 views
d

By. Jacob

Edited: 2023-11-20 23:11

{% if app.request.query.get('test') == 'some-test-value' %}
  {{ dump() }}
{% endif %}

The above technique allows you to access HTTP GET request parameters from Shopware's storefront .twig files, which is useful when you need to render something in your end- .html files based on the presence of specific query string parameters.

Another instance where this is useful, is when you want to test something in your live environment without your users noticing it. Of course, doing that is not recommended, as you risk breaking things or revealing sensitive information to users if you are not careful. Given you understand the risks, and you know to be careful, I still recommend against doing it, because I have, myself, accidentally broken things – it is bound to happen if you use the technique I reveal to you here.

Nevertheless, if you really want to do it anyway, I am not going to stop you. Admittedly I still use this technique myself from time to time. Please note though, the best way to test things is to do so in a safe test environment. You could, simply, load all of your files and your database into a Docker environment and perform your tests from localhost instead of taking risks with your live environment.

Accessing URL GET parameters

This line of code is attempting to access the value of the test query parameter in the URL. If the URL is something like http://example.com/page?test=something, then app.request.query.get('test') would retrieve the value, in this case "something".

{% if app.request.query.get('test') == 'some-test-value' %}
  {{ dump() }}
{% endif %}

Attempting to access an non-existent query string parameter will result in a null value. You can check if a given parameter exists like this:

{% if app.request.query.get('test') %}
  {{ dump() }}
{% endif %}

And, verify that it is not null like this:

{% if app.request.query.get('test') is not null %}
  {{ dump() }}
{% endif %}

Tell us what you think:

  1. Sometimes we may to manually clear cached Shopware files to fix namespace issues.
  2. How to obtain the currently selected API language from Shopware vue components.
  3. How to access file system paths from storefront twig files in Shopware.
  4. How to get or change the currently selected sales channel in an Shopware sw-sales-channel-switch component.
  5. In this tutorial you will learn how to work with Shopware entities in a generic way from PHP, without having to specifically inject the repository in your services.xml file.

More in: Shopware