I would like to translate a sentence with a word hyperlinked to an url
inside the tags of <p>
. What I am trying to translate in Django:
<p><a href="{% url 'register' %}"><strong>Register</strong></a> and be happy</p>
I tried the following:
{% blocktrans %}
<p><a href="{% url 'register' %}"><strong>Register</strong></a> and be happy</p>
{% endblocktrans %}
This yields an error as it is not possible to have another ‘{%’ inside the blocktrans
.
{% blocktrans with link={% url 'register' %} %}
<p><a href="{{ link }}"><strong>Register</strong></a> and be happy</p>
{% endblocktrans %}
Second attempt is based on this answer, but it does not work either.
Any idea how to make it work?
2
Answers
you can do it using {% trans %}
That looks like nested template tags:
The
{% url 'register' %}
tag is nested inside the{% blocktrans %}
tag. I do not think Django’s template engine would support that: it would attempt to parse theblocktrans
tag and encounters another tag (url
) inside of it, leading to an error, as illustrated here.In the second attempt, it seems like you were trying to find a way around this by assigning the URL to a variable
link
within theblocktrans
:But this also does not work because you are still trying to use a template tag (
url
) inside the parameter of another template tag (blocktrans
).I would first resolve the URL and assign it to a variable.
Then use that variable inside the
blocktrans
tag, inspired from this answer.That way, you are not trying to nest template tags, and it should work as expected.