5

I am trying to form a url parameter (for Google Maps API) from entry field data. Basically, this is what I would like to do:

{% set street = entry.address %}

{% set  city = entry.city %}

{% set urlParam = street.", ".city.", UT"  %}

Is this possible with Twig and, if so, what is the proper syntax for concatenating multiple variables and strings?

Thanks!

1
  • Can you clarify the title to say something along the lines as to where you are try to do this, such as "in a template". Commented Nov 27, 2014 at 19:30

3 Answers 3

9

Another option is to use the twig join filter:

{% set urlParam = [street, city, 'UT']|join(', ') %}

join concatenates the items in the sequence with the separator of your choice in between.

3
  • 2
    For things like addresses I usually use |filter|join(', ') so there are no repeated commas if any of the fields are null or empty. Commented Nov 25, 2014 at 20:58
  • Thanks, Marion - that seems to make a lot more sense than my approach!
    – Roi Agneta
    Commented Nov 26, 2014 at 22:29
  • mark me correct? Commented Nov 27, 2014 at 19:31
8

Figured it out! Proper syntax is:

{% set urlParam = street ~", " ~city ~", UT"  %}
2

Just wanted to add another example to this since this post help point me in the right direction.

In my example, I am getting back a list of events from a 3rd party. All that is returned to me is the slug. But, you can see that I wanted the url to be prepended with /event-results/.

<a href="{{ url('/evnet-results/'~event.slug) }}">{{ event.title }}</a>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.