skip to Main Content

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


  1. you can do it using {% trans %}

    <a href="{% url 'home' %}">{% trans 'Home Page' %}</a>
    
    Login or Signup to reply.
  2. That looks like nested template tags:

    {% blocktrans %}
        <p><a href="{% url 'register' %}"><strong>Register</strong></a> and be happy</p>
    {% endblocktrans %} 
    

    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 the blocktrans 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 the blocktrans:

    {% blocktrans with link={% url 'register' %} %}
        <p><a href="{{ link }}"><strong>Register</strong></a> and be happy</p>
    {% endblocktrans %}
    

    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.

    {% url 'register' as register_url %}
    {% blocktrans with link=register_url %}
        <p><a href="{{ link }}"><strong>Register</strong></a> and be happy</p>
    {% endblocktrans %}
    

    That way, you are not trying to nest template tags, and it should work as expected.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search