user2143356
user2143356

Reputation: 5597

Using variables inside Twig functions

I just can't get this to work:

It should set var_2 based on the URL query string value of var_1

The problem is where I call var_1 with {{var_1}}

I've tried various other methods but all throw different errors.

// var_3 set elsewhere

{% set var_1 %}test-{{var_3}}{% endset %}

{% set var_2 = app.request.get({{var_1}}) %}

// need var_2 set for rest of script

Upvotes: 1

Views: 4222

Answers (2)

caponica
caponica

Reputation: 3948

You don't need to (and often cannot) use {{ }} within twig logic. {{ }} is used to output something to the response. To use a variable in line just name the variable. Also remember that ~ will join strings, but some people don't like using it for some reason!

{% set var_1 = 'test-' ~ var_3 %}
{% set var_2 = app.request.get(var_1) %}

Upvotes: 0

Wouter J
Wouter J

Reputation: 41934

You can't use another tag ({{ ... }}) inside a twig tag ({% ... %}). So this is not going to work:

{% set var_2 = app.request.get({{var_1}}) %}

A solution is to just put the variable in function argument:

{% set var_2 = app.request.get(var_1) %}

Upvotes: 5

Related Questions