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>
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With