Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare variables inside Django templates

Tags:

django

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>
like image 864
Y7da Avatar asked Jan 10 '16 19:01

Y7da


People also ask

How to create a variable in Django templates?

In your templates folder create a file named index.html This is a basic HTML file the odd thing out here is the variable { { insert_me }}, Any text surrounded is pair of curly braces is a variable in Django templates. We will see this variable in action just in a bit.

How do I find the template directory in Django?

Tell Django where the templates are housed in your settings.py create a variable named TEMPLATE_DIR under the BASE_DIR. This will yield an absolute path to the templates directory of our project irrespective of OS.

How to declare variables in a Python template?

Another approach to declare variables in the template is by using custom template tags. Create a custom template tag files named as custom_template_tags.py . Paste the below code in it.

What does a dot mean in a variable in Django?

When the Django template engine encounters a variable, it replaces that variable with the same variable passed in the template engine. An underscore or a dot (but they must not start with a dot or underscore). A dot in a variable name has a special meaning during template rendering.


2 Answers

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.

like image 158
Saturnix Avatar answered Jan 03 '23 22:01

Saturnix


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.

like image 34
Fasand Avatar answered Jan 03 '23 23:01

Fasand