Twig: different text when url-parameter is not supplied

Hi,

I’m starting my journey in replacing dynamic content with Twig.
Using DC, this works in a text field: Bedankt {{ url.param({"key":"firstname"}) }}!
When I write this Twig-style, it doesn’t: Bedankt {{ url.param.firstname | default("") }}
What am I missing here?

Secondly, I want to achieve something that I think hasn’t been possible with DC, but is with Twig:

  • if the parameter ‘firstname’ is not present the text should state Bedankt!
  • if the parameter ‘firstname’ is present text should state Bedankt {{first name}}!

The challenge on this second question: only insert a blank space when the url-parameter is present.

Looking forward to the answers on both questions!

Hello @dhunink,

Thank you for the inquiry.

Please check the following documentation and look for the Flow Control section: https://theme.co/docs/twig

Example:

{% if url.param.firstname != "" %}
    Bedankt {{ url.param.firstname }}!
{% endif %}

Both templates should be working. What happens when you remove the fallback or default filter?

Best regards.

Hi @Ismael,

That flow control part is amazing, thanks.
However, things don’t yet work as expected.
In this example, the first (traditional) way works, but the Twig way, doesn’t.

{{ url.param({“key”:“firstname”}) }}

{% if url.param.firstname != “” %}
Bedankt {{ url.param.firstname }}!
{% else %}
Bedankt!
{% endif %}

Visiting mywebsite/?firstname=Dennis will show:

What am I missing here, in regards to the Twig implementation of grabbing that URL Parameter?

1 Like

url.param is only accessible through the key argument like in your first example. It escapes all request values to prevent malicious behavior. We can probably setup a system where you could grab it through url.param.firstname safely, but it doesn’t work that way currently. Have a great day.

Hi @charlie, thanks for clearing that up.
I’ve altered the code so it uses the key argument again and that works. Posted the code here below, in case anyone ever finds this thread and needs a solution.

Perhaps something to add to the roadmap, make url.param.key work just like other Twig statements?

{% if url.param({"key":"firstname"}) != "" %}
    Bedankt {{ url.param({"key":"firstname"}) }}!
{% else %}
		Bedankt!
{% endif %}

Hey @dhunink,

We really appreciate you for sharing the code. It will be helpful for other users as well.

Best Regards.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.