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.
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: