Reputation: 10618
I am trying to urlencode
a translated block of text that contains variables in a Django (1.6.1) template. I need to do this because of a mailto
link that contains a translated subject:
<a href="mailto:[email protected]?subject=_('Hello {{ username }}')|urlencode">Send email</a>
Except this code produces the following output:
<a href="mailto:[email protected]?subject=Hello%20%7D%7Dusername%7D%7D%20">Send email</a>
So, obviously, the username
variable was not evaluated by the _()
operator. If I'm not mistaken, the only translation tag that can evaluate variables is blocktrans
.
So, what would be great would be to store the subject translation in a dedicated variable. Something like:
{% blocktrans as subject %}Hello {{ username }}{% endblocktrans %}
<a href="mailto:[email protected]?subject={{ subject|urlencode }}">Send email</a>
Except that "as" is not a valid argument for blocktrans
.
I am aware that I could solve this with javascript. I am looking for a more "Djangonic" solution.
Upvotes: 1
Views: 603
Reputation: 905
Try escaping the translation on the pinch brackets:
<a href="mailto:[email protected]?subject=_('Hello \{\{ username \}\}')|urlencode">Send email</a>
I hope this helps.
Upvotes: 0
Reputation: 5666
You probably have to do this outside of template. Either with templatetag or in view. In any case... Instead of:
<a href="mailto:[email protected]?subject=_('Hello {{ username }}')|urlencode">Send email</a>
you need something like this:
import urllib
d = {'subject':ugettext(u"Hello %s" % username)}
and change the subject part for
value = urllib.urlencode(d)
'<a href="mailto:[email protected]?%s">Send email</a>' % value
If you are translating "hello" by the way, then you should probably consider translating "Send email" too :P
Upvotes: 1