18

I'm trying to concatenate some strings to format a URL inside my template tag, but I don't find an elegant way.

So far, what I have is:

{% button "Activate" "http://" site.domain url 'registration_activate' activation_key %}

Is there any best practice to make it a bit more "readable"?

Thanks a lot

jhagege
  • 1,486
  • 3
  • 22
  • 36

2 Answers2

25

You can concatenate two strings in Django template as follows:

{{"First String "|add:"Second String"}}

Just replace the two strings with your own variable.

Pang
  • 9,564
  • 146
  • 81
  • 122
Zahid Sumon
  • 426
  • 5
  • 6
8

What I use when I want to concatenate strings in Django templates from variables (examples taken from my own code, tell me if you need something closer to your case):

<html>
<input id="myid_{{idBase}}_{{idFinal}}" type="checkbox"></input>
</html>

and inside a django tag, I use the keyword "add" associated with the keywork with

{% with 'images/'|add:file_name as image_static %}
     <img src="{% static image_static %}" title = "{{ tooltip }}"  alt = "{{ title }}"/>
{% endwith %}
Julien Greard
  • 969
  • 1
  • 12
  • 32
  • This is already more elegant. What should I do to have |add:url 'registration_activate' activation_key? It expects the "as" keyword and can't resolve the url in this way. Thanks – jhagege Dec 30 '14 at 16:36
  • {% url 'registration_activate' activation_key as activation_url %} I didn't find any more elegant.. Do you think it's best practice? – jhagege Dec 30 '14 at 16:40