[Solved]-How to declare variables inside Django templates

21👍

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.

19👍

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.

👤Fasand

11👍

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>
👤Sayse

Leave a comment