Django variable substitution in the include template tag

2.1k views Asked by At

I have an internationalized Django 1.3 site and want to do this:

{% include "snippets/button.html" with button_text=_("Logout {{ user.username }} now") %}

And snippets/button.html looks like this:

<button
  type="{{ button_type|default:_('submit') %}"
  class="all_my special classes"
  {% if button_title %} title="{{ button_title }}"{% endif %}>
  <span class=ui-button-text>{{ button_text|default:_("Submit") }}</span>
</button>

The only way I can see to do this is something like:

{% include "snippets/button.html" with button_text="Logout "|add:user.username|add:" now" %}

But this is not acceptable as the strings to translate need to include where the variable substitution will occur. I have seen Interpolate Django template include variable but that doesn't cover this usage.

2

There are 2 answers

0
n3storm On

Something like this may let you go on:

{% blocktrans with value|filter as myvar %}
  This will have {{ myvar }} inside.
{% endblocktrans %}

from here http://www.djangobook.com/en/1.0/chapter18/

It should work with includes, but I haven't tested.

0
Thierry J. On

I think your best bet in this case is to add the already translated string to your context.

In your views.py:

...
'button_text': _("Logout {} now").format(user.username),
...

Then in your template:

{% include "snippets/button.html" with button_text=button_text %}