Y7da
Y7da

Reputation: 433

How to declare variables inside Django templates

How do I declare a variable in Django 1.8 Templates for example like this:

{% my_var = "My String" %}

And so that I can access it like this:

<h1>{% trans my_var %}</h1>

Edit:

To demonstrate my purpose of this, this is my code:

{% my_var = "String Text" %}

{% block meta_title %}{% trans my_var %}{% endblock %}

{% block breadcrumb_menu %}
{{ block.super }}
<li>{% trans my_var %}</li>
{% endblock %}

{% block main %}

<h1>{% trans my_var %}</h1>

Upvotes: 12

Views: 53700

Answers (3)

Sayse
Sayse

Reputation: 43300

You can assign the translation to a variable which you can use throughout.

 {% trans "my string" as my_var %}
 {{ my_var }}   {# You can use my_var throughout now #}

Documentation for trans tag which is an alias for translate tag, after Django-3.1


Full example with your code snippet

{% trans "String text" as my_var %}

{% block meta_title %}{{ my_var }}{% endblock %}

{% block breadcrumb_menu %}
{{ block.super }}
<li>{{ my_var }}</li>
{% endblock %}

{% block main %}

<h1>{{ my_var }}</h1>

Upvotes: 12

Fasand
Fasand

Reputation: 446

One way I like to use is:

{% firstof "variable contents" as variable %}

Then you use it as {{variable}} wherever you want without the necessity for nesting with blocks, even if you define several variables.

Upvotes: 21

Saturnix
Saturnix

Reputation: 10564

Try using the with tag.

{% with my_var="my string" %}
{% endwith %}

The other answer is more correct for what you're trying to do, but this is better for more generic cases.

Those who come here solely from the question title will need this.

Upvotes: 21

Related Questions